Home > Net >  File upload using ASP.NET and HTML form
File upload using ASP.NET and HTML form

Time:01-25

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  id="NewTRModal" role="dialog" data-backdrop="static" data-keyboard="false">
  <div  style="width:1250px;">
    <div >
      <div >
        <div>
          <label for="file-upload" >
            Upload Image1
          </label>
          <input id="file-upload" type="file" name="image1"/>
        </div>
        <div>
          <div >
          <button type="submit" > Submit</button>
          <button type="button" id="btnHideModal" >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.

CodePudding user response:

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"]; 
    ....
}
  • Related