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

18,705

Solution 1

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

Solution 2

When I implement such a thing, I use

var fd = new FormData();
fd.append(file.name,file);

And in the ajax call, send the fd.

Share:
18,705
Ricky
Author by

Ricky

Since I 'surfed' the web for the first time, the Internet has become one of my main passions, making me choose a career in this area. My other passions are music, cinema, TV shows, learning, eating white chocolate, cooking 'francesinhas' (mail me if you're curious about that), playing around with Photoshop and Illustrator, programming, social networking and, as an eternal fan of the X-Files, I love a good conspiracy. As a young and healthy man, I love sports and practice as much as I can off-road biking, hiking and jogging. In a professional standpoint, I'm a Front-end Developer, but I like to be known as a World Wide Web Worshipper :) Among working with clients from various business areas and markets, I'm currently working on a personal e/m-Commerce project for the retail and consumer industry.

Updated on June 28, 2022

Comments

  • Ricky
    Ricky almost 2 years

    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
        }
    }
    
  • Ricky
    Ricky almost 11 years
    after making that change the handler wasn't called, what could be the problem?
  • kobigurk
    kobigurk almost 11 years
    possibly a client side error. If you have a live example, that would be great. If not, and you're using chrome/firefox, check the debugger console and let me know what you see there.
  • Ricky
    Ricky almost 11 years
    in the console i get the following error: Uncaught SyntaxError: Not enough arguments i've uploaded the demo so you can give it a try: online demo
  • kobigurk
    kobigurk almost 11 years
    I corrected my answer - I mistakenly omitted the first argument, the file name.
  • Ricky
    Ricky almost 11 years
    now i'm getting this error:POST http://localhost:10081/FileUpload.ashx 500 (Internal Server Error) x.support.cors.e.crossDomain.send x.extend.ajax sendFile (anonymous function) x.event.dispatch y.handle
  • kobigurk
    kobigurk almost 11 years
    Now it's a server side error - could you show us your logs? If your exception wasn't caught, the error will appear in the event log
  • urbanlemur
    urbanlemur about 10 years
    Thanks for posting this ... it worked awesome for me
  • JakePlatford
    JakePlatford over 6 years
    Perfect, other 'solutions' I've found online haven't seemed to work for me but this did.