Reputation: 5293
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.
Upvotes: 0
Views: 1788
Reputation: 7511
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"
.
Upvotes: 0
Reputation: 6398
Rename your name
attribute of input type file
<input type="file" name="files" id="file" multiple="multiple" />
for second error i.e 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.)
Upvotes: 1