Search code examples
c#asp.netajaxhandlerashx

Unable to upload multiple files in .ashx handler


System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Web.HttpPostedFile'

This is the error that shows up in my response header. I can't send multiple files through ajax to the handler.

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);
                }
            });

Handler:

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

Solution

  • I was having the same problem. I don't know why, but the problem arises when iterating over the context.Request.Files collection with a foreach loop.

    Instead, use a traditional for loop and explicitly cast to an HttpPostedFile instead.

    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);
    }
    

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