0

I'm trying to use the Dropbox API to send files to a specific Dropbox folder via a web interface using Ajax.

Here is my code:

function UploadFile(token, callback) {

    var fileName        = $('input[type=file]')[0].files[0].name,
        fileData        = new FormData($('#file-upload')[0]),
        dbxHeaderParams = {
            'path': '/' + fileName,
            'mode': { '.tag': 'add' },
            'autorename': true
        };

    $.ajax({
        url: 'https://content.dropboxapi.com/2/files/upload',
        type: 'POST',
        headers: {
            'Authorization': 'Bearer ' + token,
            'Content-Type': 'application/octet-stream',
            'Dropbox-API-Arg': JSON.stringify(dbxHeaderParams)
        },
        data: fileData,
        processData: false,
        contentType: false,
        success: function(result) {
            console.log('NICE BRO');
            callback();
        },
        error: function(error) {
            console.error(error);
            callback();
        }
    });

}

This code works: files are uploaded to my Dropbox folder and i can open them. They even have the right name and (almost) the right size. But the problem is that they are all corrupted because some lines are added during the process.

Here is an example: if I want to upload a .txt file containing this:

harder better faster stronger

Once uploaded on my Dropbox, it will looks like this:

-----------------------------2308927457834
Content-Disposition: form-data; name="file"; filename="test.txt"
Content-Type: text/plain

harder better faster stronger
-----------------------------2308927457834--

I assume this is why I can't open files like images. I've tried several solutions but none of them can solve this. What am I doing wrong ? Thanks !

Flobesst
  • 1,281
  • 1
  • 16
  • 26

1 Answers1

1

Seeing the relevant pieces of the HTML would be useful, but it looks like the issue is that you're supplying a FormData object to the upload call, as opposed to the File.

Try replacing this line:

        fileData        = new FormData($('#file-upload')[0]),

with this:

        fileData        = $('input[type=file]')[0].files[0],
Greg
  • 16,359
  • 2
  • 34
  • 44
  • That did the trick, thanks ! But I still don't understand why it needs a `File` type here because almost every examples I found on the Web were using `FormData` objects like this (very) popular question: http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously?rq=1 – Flobesst Jul 26 '16 at 08:06