开发者

File uploader in asp.net mvc

How can identify input (type="file") id of fileupload while file uploading to server.

Let me explain in detail:

I have multiple file upload control on my page and d开发者_StackOverflowifferent control save file on different folders like "Fileupload1" will save file on "Folder1" and so on.


You can't. The id of an HTML element is never sent to the server when posting a form. As far as the name attribute is concerned you may loop through the Request.Files collection. In ASP.NET MVC it more common to use action parameters. Example:

<form action="" method="post" enctype="multipart/form-data">
  <input type="file" name="files" id="file1" />
  <input type="file" name="files" id="file2" />
  <input type="file" name="files" id="file3" />
  <input type="submit" value="Upload files" />
</form>

and your controller action:

[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"), fileName);
            file.SaveAs(path);
        }
    }
    return RedirectToAction("Index");
}

It's as simple as that.


As Darian points out, the ID isn't sent. But the name attribute is, so your file upload should be something like:

<input type="file" name="contactsFile" />

Which will let you use a method such as

public ActionResult UploadFile(HttpPostedFileBase contactsFile)

in your controller.


You won't have access to any DOM element since ASP.NET MVC uses the FileCollectionModelBinder to create a collection of files. So what you receive in your controller won't have anything to do with the DOM. But the good thing is since it's a collection you can access the index of the file.

  <input type="file" name="files[0]" id="file1" />
  <input type="file" name="files[1]" id="file2" />
  <input type="file" name="files[2]" id="file3" />

Then if you need to upload files[0] to folder Y and files[1] to folder Z you can access the files collection index.

switch (index)
{
   case 0:
   // Upload to Y
   case 1:
   // Upload to Z
   default:
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜