从浏览器使用Dropbox v2 API

mib*_*tec 0 javascript dropbox-api

我正在尝试通过webbrowser(FF 42.0,PhantomJS 1.9.8)和Dropbox v2 API将数据上传到Dropbox。我的功能看起来像这样

function(path, data, callback) {
        $.ajax({
            url: 'https://content.dropboxapi.com/2/files/upload',
            type: 'post',
            contentType: 'application/octet-stream',
            beforeSend: function(jqXHR) {
                jqXHR.setRequestHeader("Content-Type","application/octet-stream");
            },
            data: data,
            headers: {
                "Authorization": "Bearer " + token,
                "Dropbox-API-Arg": '{"path": "' + path + ',"mode": "add","autorename": true,"mute": false}',
                "Content-Type": "application/octet-stream"
            },
            success: function (data) {
                callback(data);
            }
        });
    }
Run Code Online (Sandbox Code Playgroud)

甚至我在所有可以想到的属性上都设置了Content-Type时application/octet-stream,出现以下错误

Error in call to API function "files/upload": Bad HTTP "Content-Type" header: "application/octet-stream
; charset=UTF-8".  Expecting one of "application/octet-stream", "text/plain; charset=dropbox-cors-hack"
Run Code Online (Sandbox Code Playgroud)

看一下Firebug中的请求,我发现Content-Type确实设置为application/octet-stream; charset=UTF-8。当尝试text/plain; charset=dropbox-cors-hack使用Content-Type时,已发送的请求具有text/plain; charset=UTF-8,并且出现相同的错误消息。

我该如何使jquery和我的浏览器设置所需的标题。

编辑:Chrome IE中的相同行为按预期工作

Gre*_*reg 5

从技术上讲,Firefox只是遵守W3C XMLHttpRequest规范:

http://www.w3.org/TR/XMLHttpRequest/#the-send()-方法

发送除Blob或以外的任何内容,ArrayBufferView可能会导致浏览器尝试以UTF-8编码数据(遵循规范)时出现问题。

正确的做法是避免将数据作为字符串发送。下面是两个如何避免此行为的示例:

// ... file selected from a file <input>
file = event.target.files[0];
$.ajax({
    url: 'https://content.dropboxapi.com/2/files/upload',
    type: 'post',
    data: file,
    processData: false,
    contentType: 'application/octet-stream',
    headers: {
        "Authorization": "Bearer " + ACCESS_TOKEN,
        "Dropbox-API-Arg": '{"path": "/test_ff_upload.txt","mode": "add","autorename": true,"mute": false}'
    },
    success: function (data) {
        console.log(data);
    }
})
Run Code Online (Sandbox Code Playgroud)

或者,如果您要发送文本,则可以在上传自己之前对文本进行UTF-8编码。一种现代的方法是使用TextEncoder

var data = new TextEncoder("utf-8").encode("Test");
$.ajax({
    url: 'https://content.dropboxapi.com/2/files/upload',
    type: 'post',
    data: data,
    processData: false,
    contentType: 'application/octet-stream',
    headers: {
        "Authorization": "Bearer " + ACCESS_TOKEN,
        "Dropbox-API-Arg": '{"path": "/test_ff_upload.txt","mode": "add","autorename": true,"mute": false}'
    },
    success: function (data) {
        console.log(data);
    }
})
Run Code Online (Sandbox Code Playgroud)