0

I have tried several things to get my image data from the file input and send it to the NodeJS server but nothing has helped me so far. I had a lot of different solutions with formData, FileReader etc. but I never had my data.

My HTML is following:

<button type="button" id="uploadButton" onclick="openFilepicker()">
Upload file
</button>

The openFilepicker() function triggers a click via jQuery on the file-input element:

<form id='uploadForm' encType="multipart/form-data">
    <input type="file" accept="image/*" name="uploader" class="hidden" 
    id="input-file" onchange="submitUploadForm()"/>
</form>

The submitUploadForm() function gets executed when a file has been selected:

function submitUploadForm() {
  if ($('#input-file').val() != '') {
    const input = document.getElementById('input-file');
    const file = input.files[0];

    /* Process my data here to be ready to send it */

    $.ajax({
        url: '/upload',
        type: 'POST',
        data: '', /* Here I want my file data to be sent */
        cache: false,
        contentType: false,
        processData: false,
        success: function (data) {
            console.log(data);
        }.bind(this),
        error: function (err) {
            console.log(err);
        }.bind(this)
    });
  }
}
Wulthan
  • 417
  • 2
  • 6
  • 19
  • It is not a duplicate of [this](http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously) because it did not work for me. – Wulthan Mar 02 '17 at 10:29
  • 1
    Just because it doesn't work for you doesn't mean it's not the correct answer. You need to upload the binary file data using a `FormData` object, exactly as the duplicate shows. You can then deal with it on the server as needed. – Rory McCrossan Mar 02 '17 at 12:41
  • @RoryMcCrossan Logging my FormData Obj shows an empty Obj {} - so I'm not able to fill it – Wulthan Mar 02 '17 at 12:47
  • 1
    You cannot view the content of a FormData object in the console as it's binary. It will have been filled correctly though – Rory McCrossan Mar 02 '17 at 12:47
  • 2
    Yeah, I just realized that, I was stuck all the time at that point trying to figure out why it's empty, now I just handled it on the server and it is actually filled correctly, thanks – Wulthan Mar 02 '17 at 12:51

0 Answers0