简体   繁体   English

如何在ASP.NET MVC3中使用HttpFileCollectionBase实现多个文件选择和上传?

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

I have implemented the multiple file selection using PLUpload framework. 我已经使用PLUpload框架实现了多个文件的选择。

It is possible to get Request.Files in controller to be passed to model (there will process the files) ? 是否有可能在控制器中获取Request.Files传递给模型(将处理文件)?

I know that Request.Files get automatically the all input type='file' tags from the page. 我知道Request.Files会自动从页面获取所有input type='file'标记。

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: 示例:选择两个文件后,我在HTML代码中具有以下标记:

<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: 以及上传器表单的HTML代码:

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

Assuming the name of the file input is for example files you could have the following controller action: 假设文件输入的名称是例如files您可以执行以下控制器操作:

[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. 看来您要使用PLUpload插件。 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 });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM