从上传的多个文件中获取文件名
我的表单中有4 fileupload
。 我想当我点击一个按钮,我得到文件名并设置为model,然后将文件上传到服务器。 但我不想要使用4个文件,我可以选择一次使用3个,2个或1个文件上传。 如果我只使用2个文件上传,则file3和file4模型仍然为null。 我必须在我的控制器中做什么?
有什么想法或建议吗?
模型:
public string file1 {get;set;} public string file2 {get;set;} public string file3 {get;set;} public string file4 {get;set;}
视图:
@using (Html.BeginForm("action", "controller", FormMethod.Post, new { enctype = "multipart/form-data" })) { }
在你的视图中:
注意: 此处不需要您的型号名称。 通过动作结果参数,您将传递您的文件。
@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) { }
在您的控制器中:
[HttpPost] public ActionResult FileUpload(HttpPostedFileBase file1, HttpPostedFileBase file2, HttpPostedFileBase file3, HttpPostedFileBase file4) // OR IEnumerable 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(); }
在Codeproject中有一篇关于文件上传的文章。 我没有检查上面的代码。 如果没有成功,请告诉我。