Search code examples
c#file-uploadasp.net-apicontroller

Upload file doesn't work in ApiController c#


I have a C# application with a form to upload an image but the call goes to the controller I cannot take the upload file. Request.Content.IsMimeMultipartContent() is false, file.Count() = 0 and file2 is a string.

@model Form
<div class="form-wrapper">
    <h3>@Model.Title</h3>
    @if (!string.IsNullOrEmpty(Model.Intro))
    {
        <p>@Html.Raw(Model.Intro)</p>
    }

    <form class="form"
          enctype="multipart/form-data"
          novalidate
          data-required-label="@Html.GetLabel("form-required-field")"
          data-required-group-label="@Html.GetLabel("form-choice-makechoice")"
          data-api-endpoint="/api/form">

        <input id="test" name="test" type="file" required/>
        <input type="hidden" name="tcm" readonly value="@Model.TcmUri">
        <p class="form-section form-section--submit">
            <button class="btn-primary--with-icon-internal" type="submit">@Html.GetLabel("form-submit-button")</button>
        </p>
    </form>
</div>


[System.Web.Http.RoutePrefix("api/form")]
public class ApiFormController : ApiController
{
    public ApiFormController()
    {
    }

    [System.Web.Http.Route("")]
    [System.Web.Http.HttpPost]
    public async Task<HttpResponseMessage> Form()
    {
        if (Request.Content.IsMimeMultipartContent())
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

        var file = HttpContext.Current.Request.Files;
        var requestForm = HttpContext.Current.Request.Form;
        var file2 = requestForm["test"];
    }
}

Solution

  • this code enctype="multipart/form-data" in form tag used for this if (Request.Content.IsMimeMultipartContent()). It is better to clean it.

    I modified the code. first, Do not change the form. If the answer does not work, use the definition of the form below

    Step 1

    create ApiFormController.cs

    public class ApiFormController : ApiController
    {
        public ApiFormController()
        {
        }
    
        [System.Web.Http.HttpPost]
        public async Task<HttpResponseMessage> Form()
        {
           var files = HttpContext.Current.Request.Files;
    
           //one file
           HttpPostedFile postedfile = files.Get("test");
    
           //multi file
           List<HttpPostedFile> postedfiles = new List<HttpPostedFile>();
           foreach (var item in files)
           {
               postedfiles.Add(files.Get(item.ToString()));
           }
           
           //save file
           postedfile.SaveAs(Path.Combine("~/uploadfiles/", postedfile.FileName));
           return new HttpResponseMessage(HttpStatusCode.OK);
        }
    }
    

    Step 2

    create WebApiConfig.cs

    public static class WebApiConfig
    {
       public static void Register(HttpConfiguration config)
       {
         config.MapHttpAttributeRoutes();
    
         config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/form",
            defaults: new { controller = "ApiForm", action = "Form" }
          );
       }
    }
    

    Step 3

    register WebApiConfig class in global.cs

    protected void Application_Start()
    {
         //...........
         GlobalConfiguration.Configure(WebApiConfig.Register);
         //..........
    }
    

    Step 4

    create view

    <form class="form"
             enctype="multipart/form-data" action="/api/form" method="post">
    
          <input id="test" name="test" type="file" />
          <br />
          <input type="file" name="test1" id="test1" />
          <p class="form-section form-section--submit">
              <button class="btn-primary--with-icon-internal" type="submit">Upload Files</button>
          </p>
    </form>