简体   繁体   中英

Issue in Uploading multiple files using c#

I am trying to upload multiple files, (selecting multiple files in a single click and upload). For that I am using the following code. I am doing this in MVC4

@using (Html.BeginForm("Gallery", "Admin", FormMethod.Post, new  {enctype="multipart/form-data", id = "GalleryForm" }))
{
    @Html.ValidationSummary();

    <div> Select the files to Upload<br /> <input type="file" name="file" id="file" multiple="multiple" /><br /><br /></div>
    <div><input type="submit" name="submit" Value="Save"/></div>
}

Controller

[HttpPost]
public ActionResult Gallery(IEnumerable<HttpPostedFileBase> files)
{
    foreach (var file in files)
    {
        if (file.ContentLength > 0)
        {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/Images/Gallery/"), fileName);
            file.SaveAs(path);
         }
    }
    return RedirectToAction("Index");
}

If I select more than one file, I got the error "Maximum request length exceeded" and when I select single file and try to upload then, I got the error "Object reference not set to an instance of an object" . Actually, I want to upload single and multiple files using this same form. How will this be possible. Please help me. Thanks in advance.

Rename your name attribute of input type file

<input type="file" name="files" id="file" multiple="multiple" />

for second error ie maximunn length exceed change in web config

<configuration>
    <system.web>
        <httpRuntime maxRequestLength="1048576" />
    </system.web>
</configuration>

For IIS7 and above, you also need to add the lines below:

<system.webServer>
   <security>
      <requestFiltering>
         <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
   </security>
 </system.webServer>

Note: maxAllowedContentLength is measured in bytes while maxRequestLength is measured in kilobytes, which is why the values differ in this config example. (Both are equivalent to 1 GB.)

Your parameter name doesn't match your form input element name, you should use "file" or "files" in both the code behind and the html. name="file" should be name="files" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM