neel
neel

Reputation: 5293

Upload multiple images in different folders using single button

i am doing my project in mvc4 using c#

i my project i want to upload two image files from a folder so i use the following code.

View:

 <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>

Controller:

[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");
}

actually my need is that i want to upload these images in different folders on a single submit button. (That is file1 into Folder1 and file2 into Folder2) is that possible??

Upvotes: 1

Views: 1365

Answers (1)

Damian S
Damian S

Reputation: 156

You have many solutions.

 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");
    }

Upvotes: 2

Related Questions