简体   繁体   English

通过Ajax上传到Dropbox时文件损坏

[英]Corrupted files when uploading to Dropbox via Ajax

I'm trying to use the Dropbox API to send files to a specific Dropbox folder via a web interface using Ajax. 我正在尝试使用Dropbox API通过Web界面使用Ajax将文件发送到特定的Dropbox文件夹。

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. 此代码有效:将文件上传到我的Dropbox文件夹中,我可以打开它们。 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: 这是一个示例:如果我要上传一个包含以下内容的.txt文件:

harder better faster stronger

Once uploaded on my Dropbox, it will looks like this: 一旦上传到我的Dropbox上,它将如下所示:

-----------------------------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 ! 谢谢 !

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 . 看到HTML的相关部分会很有用,但问题似乎在于您正在为上载调用提供FormData对象,而不是File

Try replacing this line: 尝试替换此行:

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

with this: 有了这个:

        fileData        = $('input[type=file]')[0].files[0],

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM