0

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.

Andrew Newby
  • 4,941
  • 6
  • 40
  • 81

2 Answers2

1

You'd need to use the FileReader API.

document.getElementById('upload-file').addEventListener("change", function(e){
    var formData = new FormData();
    var file = e.currentTarget.files[0];
    var reader = new FileReader();

    // The load event is fired each time the reading operation is successfully completed. 
    reader.onload = function(event) {
        var jsonData = JSON.parse(event.target.result);  // event.target.result is the file's data
        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) {

            }
        });  
    }

    reader.readAsText(file);
});
Shiven Sinha
  • 656
  • 5
  • 14
  • thanks for the reply. I just found this post: https://github.com/ded/reqwest/issues/135 . It seems like adding `processData: false,` does the trick :) – Andrew Newby Mar 27 '18 at 07:04
0

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 :)

Andrew Newby
  • 4,941
  • 6
  • 40
  • 81