使用单个按钮上传不同文件夹中的多个图像

时间:2013-10-22 05:25:35

标签: c# asp.net-mvc-4

我正在使用c#

在mvc4中完成我的项目

我的项目我想从文件夹上传两个图像文件,所以我使用以下代码。

查看:

 <form action="" method="post" enctype="multipart/form-data">
   <label for="file1">Filename:</label>
   <input type="file" name="files" id="file1" />
   <label for="file2">Filename:</label>
   <input type="file" name="files" id="file2" />
   <input type="submit"  />
 </form>

控制器:

[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files) {
foreach (var file in files) {
if (file.ContentLength > 0) {
  var fileName = Path.GetFileName(file.FileName);
  var path = Path.Combine(Server.MapPath("~/App_Data/uploads/Folder1"), fileName);
  file.SaveAs(path);
}
}
return RedirectToAction("Index");
}

实际上我需要的是我想在单个提交按钮上将这些图像上传到不同的文件夹中。 (即file1进入Folder1而file2进入Folder2)是可能的??

1 个答案:

答案 0 :(得分:2)

你有很多解决方案。

 public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
    {
        IList<HttpPostedFileBase> list = (IList<HttpPostedFileBase>)files;
        for (int i = 0; i < files.Count(); i++)
        {
            if (list[i].ContentLength > 0 && i == 0)
            {
                var fileName = Path.GetFileName(list[i].FileName);
                var path = Path.Combine(Server.MapPath("~/App_Data/uploads/Folder1"), fileName);
                file.SaveAs(path);
            }
            else if (list[i].ContentLength > 0)
            {
                var fileName = Path.GetFileName(list[i].FileName);
                var path = Path.Combine(Server.MapPath("~/App_Data/uploads/Folder2"), fileName);
                file.SaveAs(path);
            }
        }
        return RedirectToAction("Index");
    }