【问题标题】:How do I handle HTML5 Multiple File uploads in ASP.NET MVC?如何在 ASP.NET MVC 中处理 HTML5 多文件上传?
【发布时间】:2014-03-14 03:01:48
【问题描述】:

我找到了following great thread,其中解释了如何使用新的 HTML5 FormData API 通过 AJAX/Jquery 进行文件上传

这是该代码的略微更新版本,使用更新的 JQuery 1.8+ 语法

$(':button').click(function(){
    var formData = new FormData($('form')[0]);
    $.ajax({
        url: '/Upload',  //my ASP.NET MVC method
        type: 'POST',
        // handle the progress report
        xhr: function() {  // Custom XMLHttpRequest
            var myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){ // Check if upload property exists
                myXhr.upload.addEventListener('progress',progressHandlingFunction,    false); // For handling the progress of the upload
            }
            return myXhr;
        },

        // Form data
        data: formData,

        //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
    })
    .done(function(){
        alert("success");
    })
    .fail(function(){
        alert("error");
    });
});

function progressHandlingFunction(e){
    if(e.lengthComputable){
        $('progress').attr({value:e.loaded,max:e.total});
    }
}

这是表格

<form enctype="multipart/form-data">
    <input name="file" type="file" />
    <input type="button" value="Upload" />
</form>
<progress></progress>

在服务器端,我们有这样的东西。

[HttpPost]
public string Upload(HttpPostedFileBase file)
{
    // do something with file
    return "you uploaded a file called " + file.FileName;
}

这很好用。直到您决定在文件对话框中使用“多个”属性,并发送多个文件。

<form enctype="multipart/form-data">
    <input name="file" type="file" multiple="multiple" />
    <input type="button" value="Upload" />
</form>
<progress></progress>

您会在网上找到各种建议以下解决方案的页面

public string Upload(IEnumerable<HttpPostedFileBase> files)
{
    foreach(var file in files)
         ...
}

哎呀。没用

public string Upload(List<HttpPostedFileBase> files)
{
    foreach(var file in files)
         ...
}

不。不工作。

public string Upload(IEnumerable files)
{
    foreach(var file in files)
         ...
}

甚至不编译

public string Upload(HttpPostedFileBase[] files)
{
    foreach(HttpPostedFileBase file in files)
         ...
}

你猜怎么着?不工作。让我们尝试处理 Request.Files 。好老可靠的Request.Files。从未失败。

public string Upload()
{
    foreach (HttpPostedFileBase uf in Request.Files)
         ...
}

剧透警告:它不起作用。

啊哈。知道了!我将遍历 Request.Files 中的键。

public string Upload()
{
    foreach(var key in Request.Files.AllKeys)
    {
        var file = Request.Files[key];
    }
}

再一次,它不起作用。

【问题讨论】:

    标签: jquery asp.net ajax html file-upload


    【解决方案1】:

    的工作如下,from the blog 总是可靠且头发动态的 Rick Strahl

    public string Upload()
    {
        for (int i = 0; i < Request.Files.Count; i++)
        {
            var file = Request.Files[i];
        } 
    }
    

    这背后的原因是传递给Request.Files 的文件集合都具有相同的名称,因为它们来自一个单一的文件上传对话框。

    服务器端方法被传递一个包含文件的single 对象,出于某种原因,Request.Files 是获取它的唯一方法。

    希望我通过添加这个来避免一些头痛。

    【讨论】:

    • 文件类型呢?我想允许用户上传".jpg" , ".gif", ".png" 类型的文件...但是由于所有文件都具有相同的名称,那么我怎样才能获得任何文件的类型?
    • 您仍然可以访问文件名,但所有包含这些文件的 post variables 都具有相同的名称。将文件分配给 file 变量后,您可以检查名称和扩展名,并对其进行过滤。
    【解决方案2】:

    就我而言,对我有用的是将所有文件绑定到 ViewModel 字段。 ViewModel 将是我用于前端的模型。

    @using School.ViewModels
    @model UserProfileViewModel
    
    
    <form enctype="multipart/form-data">
    <input id="username"name="username" type="text" />
    <input name="Myfiles" type="file" multiple="multiple" />
    <input type="button" value="Upload" />
    </form>
    

    UserProfileViewModel.cs

    namespace School.ViewModels
    {
        public class UserProfileViewModel
        {
            public long Username { get; set; }
    
            public List<HttpPostedFileBase> Myfiles { get; set; }
        }
    }
    

    UserProfilePicturesController.cs

    public ActionResult Create([Bind(Include="Username,Myfilese")] UserprofileViewModel userprofileViewModel)
    {
         var files = userprofileViewModel.Myfiles;
         foreach(HttpPostedFileBase file in files)
         {
             //do something here
         }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-07
      • 2019-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      • 2011-02-07
      相关资源
      最近更新 更多