无法在.ashx处理程序中上传多个文件

时间:2014-02-17 18:18:48

标签: c# asp.net ajax handler ashx

  

System.InvalidCastException:无法转换类型的对象   'System.String'键入'System.Web.HttpPostedFile'

这是我的响应标题中显示的错误。 我无法通过ajax将多个文件发送到处理程序。

的jQuery

            var data = new FormData();
            jQuery.each($('#multipleFileUpload')[0].files, function (i, file) {
                data.append('file-' + i, file);
            });

            $.ajax({
                url: "../handlers/project/sell/galleryUpload.ashx",
                type: "POST",
                contentType: false,
                processData: false,
                cache: false,
                async: true,
                data: data,
                error: function (data) {
                    alert("Erro no envio de fotos do projecto. " + data.status);
                }
            });

处理程序:

foreach (HttpPostedFile file in context.Request.Files)
{ ... } 
//it gives error in this line

2 个答案:

答案 0 :(得分:1)

我遇到了同样的问题。我不知道为什么,但是当迭代带有foreach循环的context.Request.Files集合时会出现问题。

相反,请使用传统的for循环并显式转换为HttpPostedFile。

HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count;i++ )
{
    HttpPostedFile file = files[i];
    string fname = context.Server.MapPath("~/uploads/" + file.FileName);
    file.SaveAs(fname);
}

来源: http://www.binaryintellect.net/articles/f2a2f1ee-e18a-416b-893e-883c800f83f4.aspx

答案 1 :(得分:0)

AjaxUpload取决于浏览器,您使用的浏览器是什么?

您的表单是否包含enctype =“multipart / form-data”?

看看这个答案:

JS:How to send multiple files using FormData(jQuery Ajax)