I have a ASP.NET MVC project in which the user can upload multiple files at a time. The following code is in the View:
@using (Html.BeginForm("Edit",
"Bacteria",
FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<!--Other fields that are posted correctly to the db-->
<div class="">
<label class="control-label col-md-2">Attach New Files:</label>
<div class="col-md-10">
<input type="file" id="Attachment" name="Attachment" class="form-control" accept=".xls,.xlsx,.csv,.CSV,.png,.jpeg,.jpg,.gif,.doc,.docx,.pdf,.PDF" multiple />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
The method in the controller is:
if (ModelState.IsValid)
{
db.Entry(bacteria).State = EntityState.Modified;
db.SaveChanges();
foreach (string file in Request.Files)
{
HttpPostedFileBase hpf = Request.Files[file];
var fileName = Path.GetFileName(hpf.FileName);
if (fileName == null || fileName == "")
{
break;
}
var subPath = "Attachments/Bacteria/" + bacteria.ID + "/";
bool exists = System.IO.Directory.Exists(Server.MapPath("~/" + subPath));
if (!exists)
{
System.IO.Directory.CreateDirectory(Server.MapPath("~/" + subPath));
}
var path = Path.Combine(subPath, fileName);
hpf.SaveAs(Server.MapPath("~/" + path));
BacteriaAttachment a = new BacteriaAttachment()
{
Name = fileName,
Bacteria = bacteria,
Link = path
};
db.BacteriaAttachments.Add(a);
db.SaveChanges();
}
}
If I upload FileOne.png, FileTwo.png, FileThree.png; the BacteriaAttachements table will get 3 new records with all of them having the same name (such as FileOne.png), link and bacteriaID. Only their ID (the primary key) is unique. And only one file (E.g: FileOne.png) gets uploaded in the server.
So instead of the three files being uploaded, only one of them is being uploaded thrice.
Any help is much appreciated.
Thank you.