Search code examples
javascriptreqwest

Handling a file upload with reqwest in Javascript


I'm using the following system to handle AJAX uploads: https://github.com/ded/reqwest

While it works for everything I've tried so far - I now need to do a file upload (when the input gets changed). How do you go about it? So far I have:

document.getElementById('upload-file').addEventListener("change", function(e){

    var formData = new FormData();
    var file = e.currentTarget.files[0];

    reqwest({
        url: '/cgi-bin/upload.cgi',
        type: 'json',
        method: 'post',
        headers: {
              'enctype': 'multipart/form-data'
            },
        data: { the_file: file },
        error: function (err) {
            alert("There was an error: " + err)
        },
        success: function (data) {

        }
    });


});

Unfortunatly, that just sends:

the_file [object+File]

...with no data attached to the file.


Solution

  • I just found the answer here:

    https://github.com/ded/reqwest/issues/135

    It turns out you need:

    processData: false, // important
    

    So the full code:

    reqwest({
        url: '/cgi-bin/upload.cgi',
        type: 'json',
        method: 'post',
        processData: false, // important
        headers: {
              'enctype': 'multipart/form-data'
            },
        data: fd,
        error: function (err) {
            alert("There was an error: " + err)
        },
        success: function (data) {
    
        }
    });
    

    It sends the file perfectly now :)