views:

54

answers:

3

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 different control save file on different folders like "Fileupload1" will save file on "Folder1" and so on.

+3  A: 

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.

Darin Dimitrov
I have multiple file upload to upload file on server then how can i identify the file to related input.suggest if u have idea.
Xulfee
how can i get name of input?
Xulfee
But it doesn't return and name of input
Xulfee
A: 

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.

Wyatt Barnett
Can u provide me sample code which explain in detail.
Xulfee
A: 

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:
}
JeremySpouken
can u provide me sample code which explain in detail
Xulfee