I have built a website using asp.net 4.5 and MVC 5. In one of my views I want to upload multiple files. With my code below, the first fileis collected and saved, but it is saved as many times as the number of files I try to upload.
For example: I choose the files pic1.jpg and pic2.jpg with the file uploader. This results in the file pic1.jpg being saved twice.
While debugging I see that the Request.Files[file];
code returns the same file each time. It seems that I get the same file uploader twice, and that only the first file is selected.
How do I alter my code to fetch all files selected via the uploader?
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ProductViewModel product)
{
...
foreach (string file in Request.Files)
{
var hpf = Request.Files[file];
if (hpf != null && hpf.ContentLength > 0)
{
var savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.GetFileName(hpf.FileName));
hpf.SaveAs(savedFileName);
}
}
...
return RedirectToAction<ProductController>(x => x.Index());
}
View
@model EVRY.OrderCapture.Administration.ViewModels.ProductViewModel
<h2>@Resources.Resources.Create</h2>
@using (Html.BeginForm("Create", "Product", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
...
<div class="form-group">
<label for="fileUpload" class="control-label col-md-2">Filename:</label>
<div class="col-md-10">
<input type="file" name="files" id="fileUpload" multiple />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="@Resources.Resources.Create" class="btn btn-default" />
</div>
</div>
</div>
}
I found the answer to this myself. I had to select on index instead of name.