1

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

2
  • 1
    Yes, it is possible. Now what problem you have with saving each file to whatever location you want? Commented Oct 22, 2013 at 5:31
  • @AlexeiLevenkov: Then how can i rewrite my code for that, can you please tell me Commented Oct 22, 2013 at 5:34

1 Answer 1

2

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");
    }
Sign up to request clarification or add additional context in comments.

1 Comment

but i didnot get files.Length

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.