Search code examples
c#htmlasp.netasp.net-corerazor

File upload using ASP.NET and HTML form


I am trying to create the functionality that allows to upload the image and store it into the db. I have this input field in my HTML form:

@using (Html.BeginForm("AddTR", "TestCell", FormMethod.Post))
{
<div class="modal" id="NewTRModal" role="dialog" data-backdrop="static" data-keyboard="false">
  <div class="modal-dialog modal-xl" style="width:1250px;">
    <div class="modal-content">
      <div class="box5">
        <div>
          <label for="file-upload" class="custom-file-upload">
            Upload Image1
          </label>
          <input id="file-upload" type="file" name="image1"/>
        </div>
        <div>
          <div class="modal-footer">
          <button type="submit" class="btn btn-primary button button4"> Submit</button>
          <button type="button" id="btnHideModal" class="btn btn-primary button button4">Hide</button>
        </div>
      </div>
    </div>
</div>
}

And I am trying to get the file in my controller through

IFormFile file = Request.Form.Files["image1"];

However, for some reasons after I am clicking submit button the Request.Form.Files is empty.

I will appreciate any advice.


Solution

  • Web browsers will upload files properly only when the HTML form element defines an enctype value of multipart/form-data:

    @using (Html.BeginForm("AddTR", "TestCell", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        ...
        <input id="file-upload" type="file" name="image1"/>
        ...
    }
    

    Without the enctype attribute, the browser will transmit only the name of the file and not its content.

    Then in the controller action method you can use the same name as defined in the <input> tag as a parameter:

    [HttpPost]
    public ActionResult AddTR(HttpPostedFileBase image1)
    {
        if (image1 != null && image1.ContentLength > 0)   
        {
            string path = Path.Combine(Server.MapPath(@"~/"), Path.GetFileName(image1.FileName));
            image1.SaveAs(path);
        }
        ...
    }
    

    In case you are using ASP.NET Core (what you didn't mention in the question) you can define the enctype attribute and than use:

    [HttpPost]
    public IActionResult AddTR()
    {
        IFormFile file = Request.Form.Files["image1"]; 
        ....
    }