File Upload with jQuery AJAX and Handler (ashx) not working

Ricky picture Ricky · Jun 6, 2013 · Viewed 18.5k times · Source

I'm trying to upload an image file with jQuery AJAX and a generic handler. But it seems that the file isn't being passed to the handler. After submit context.Request.Files[0]; is always null :-/

What am i doing wrong?

HTML:

<form id="form1" runat="server" method="post" enctype="multipart/form-data">

    <input name="file" id="file" type="file" />
    <input id="save" name="submit" value="Submit" type="submit" />

</form>

JS:

$().ready(function ()
{
    $('#file').change(function () 
    {
        sendFile(this.files[0]);
    });
});

function sendFile(file) 
{
    $.ajax({
        type: 'post',
        url: 'FileUpload.ashx',
        data: file,
        success: function () {
            // do something
        },
        xhrFields:
        {
            onprogress: function (progress) 
            {
                // calculate upload progress
                var percentage = Math.floor((progress.total / progress.totalSize) * 100);

                // log upload progress to console
                console.log('progress', percentage);

                if (percentage === 100) {
                    console.log('DONE!');
                }
            }
        },
        processData: false,
        contentType: 'multipart/form-data'
    });
}

ASHX:

public void ProcessRequest (HttpContext context) 
{
    HttpPostedFile file = context.Request.Files[0];

    if (file.ContentLength > 0)
    {
        //do something
    }
}

Answer

Ricky picture Ricky · Feb 12, 2014

Managed to get this working :)

Here's my code...

///create a new FormData object
var formData = new FormData(); //var formData = new FormData($('form')[0]);

///get the file and append it to the FormData object
formData.append('file', $('#file')[0].files[0]);

///AJAX request
$.ajax(
{
    ///server script to process data
    url: "fileupload.ashx", //web service
    type: 'POST',
    complete: function ()
    {
        //on complete event     
    },
    progress: function (evt)
    {
        //progress event    
    },
    ///Ajax events
    beforeSend: function (e) {
        //before event  
    },
    success: function (e) {
        //success event
    },
    error: function (e) {
        //errorHandler
    },
    ///Form data
    data: formData,
    ///Options to tell JQuery not to process data or worry about content-type
    cache: false,
    contentType: false,
    processData: false
});
///end AJAX request