I have 4 fileupload
in my form. I want when I click a button, I get the file name and set to model, then the file upload to server. But i don't want must use 4 file, I can use 3, 2, or 1 file upload at a time by choice. If I only use 2 file upload, file3 and file4 model still null. what I must do in my controller ?
Any ideas or suggestion?
Model:
public string file1 {get;set;}
public string file2 {get;set;}
public string file3 {get;set;}
public string file4 {get;set;}
View:
@using (Html.BeginForm("action", "controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="files" id="file1" />
<input type="file" name="files" id="file2" />
<input type="file" name="files" id="file3" />
<input type="file" name="files" id="file4" />
<input type="submit" />
}
In Your View :
Note: Here your model names are not required. Through action result parameter you going to pass your files.
@using (Html.BeginForm("FileUpload", "Home",
FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file1" id="file1" />
<input type="file" name="file2" id="file2" />
<input type="file" name="file3" id="file3" />
<input type="file" name="file4" id="file4" />
<input type="submit" value="Upload File" id="btnSubmit" />
}
In your Controller:
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase file1, HttpPostedFileBase file2, HttpPostedFileBase file3, HttpPostedFileBase file4) // OR IEnumerable<HttpPostedFileBase> files
{
HttpPostedFileBase file1 = Request.Files["file1"];
HttpPostedFileBase file2 = Request.Files["file2"];
HttpPostedFileBase file3 = Request.Files["file3"];
HttpPostedFileBase file4 = Request.Files["file4"];
if (file1 != null) // Same for file2, file3, file4
{
//If this is True, then file1 has file.,
}
// Check and Save the file1 // Same for file2, file3, file4
if (file1.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
return View();
}
There is an article about file uploading in Codeproject.
I didn't checked the above code. Let me know if that is not getting worked.