Monday 29 June 2015

Uploading files with Asp.net MVC

Uploading a single File:
Start with view having a form that will postback to the current action

<form action="" method="post" enctype="multipart/form-data">
  <label for="file">Filename:</label>
  <input type="file" name="file1" id="file1" />
  <input type="submit" />
</form>
 
In Controller
 
[HttpPost]
public ActionResult Index(HttpPostedFileBase file1) {

  if (file1.ContentLength > 0) {
    var fileName = Path.GetFileName(file1.FileName);
    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
    file1.SaveAs(path);
  }

  return RedirectToAction("Index");
} 


"~/App_Data/uploads" is a folder to upload files on server.
 
Uploading multiple files: 

In view 

<form action="" method="post" enctype="multipart/form-data">
  <label for="file1">File name:</label>
  <input type="file" name="files1" id="file1" />
  <label for="file2">File name:</label>
  <input type="file" name="files1" id="file2" />
  <input type="submit"  />
</form>
 
In Controller:
 
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files) {
  foreach (var file1 in files) {
    if (file1.ContentLength > 0) {
      var fileName = Path.GetFileName(file1.FileName);
      var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
      file1.SaveAs(path);
    }
  }
  return RedirectToAction("Index");
} 
Here we are getting list of files so we are using IEnumerable to list the files.
So you can upload multiples files on server.

No comments:

Post a Comment