Snake Eyes
Snake Eyes

Reputation: 16764

How to implement multiple files selection and upload using HttpFileCollectionBase in ASP.NET MVC3?

I have implemented the multiple file selection using PLUpload framework.

It is possible to get Request.Files in controller to be passed to model (there will process the files) ?

I know that Request.Files get automatically the all input type='file' tags from the page.

What workaround is necessary to do ?

I don't want to upload files before submitting form. I want when submit the form then the upload will proceed as such.

Example: After selecting two files, I have the following tags in HTML code:

<div id="filelist">
  <div id="p17lu3r33g14jk1dg31u0dg1l1lll3">test.xml (272 KB) <b></b></div>
  <div id="p17lu3r33h9mt2oiel81l5t17iq4">abcde.xml (272 KB) <b></b></div>
</div>

And the HTML code for uploader form:

<div id="upload-container">
   <div>
      <a id="pickfiles" href="#">Select files</a>      
      <a id="uploadfiles" href="#">Upload selected files</a>
   </div>
   <div>
      <div id="filelist">
      </div>
   </div>
</div>

Upvotes: 0

Views: 1591

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

Assuming the name of the file input is for example files you could have the following controller action:

[HttpPost]
public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
{
    ....
}

or define a view model:

public class MyViewModel
{
    public IEnumerable<HttpPostedFileBase> Files { get; set; }
}

and then:

[HttpPost]
public ActionResult Upload(MyViewModel model)
{
    ....
}

Once again it is important to have the file input named the same. For example:

<input type="file" name="files" />
<input type="file" name="files" />
<input type="file" name="files" />
...

UPDATE:

It appears that you want to use the PLUpload plugin. This plugin sends each file individually and uses chunks. So here's an example of how you could handle the upload on the server:

[HttpPost]
public ActionResult Upload(int? chunk, string name)
{
    var fileUpload = Request.Files[0];
    var uploadPath = Server.MapPath("~/App_Data");
    chunk = chunk ?? 0;
    using (var fs = new FileStream(Path.Combine(uploadPath, name), chunk == 0 ? FileMode.Create : FileMode.Append))
    {
        var buffer = new byte[fileUpload.InputStream.Length];
        fileUpload.InputStream.Read(buffer, 0, buffer.Length);
        fs.Write(buffer, 0, buffer.Length);
    }
    return Json(new { message = "chunk uploaded", name = name });
}

Upvotes: 4

Related Questions