我正在尝试通过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);
}
});
}
即使我将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"
查看Firebug中的请求,向我显示Content-Type确实设置为application/octet-stream; charset=UTF-8
。尝试text/plain; charset=dropbox-cors-hack
作为内容类型时,已发送的请求已text/plain; charset=UTF-8
,我收到相同的错误消息。
如何让jquery和我的浏览器设置我需要的标题。
编辑:Chrome中的行为相同 IE按预期工作
答案 0 :(得分:5)
从技术上讲,Firefox只是遵循W3C XMLHttpRequest规范:
http://www.w3.org/TR/XMLHttpRequest/#the-send()-method
发送Blob
或ArrayBufferView
以外的任何内容都可能导致浏览器尝试使用UTF-8编码数据时出现问题(遵循规范)。
这里做的正确的事情是避免以String形式发送数据。以下是如何避免此行为的两个示例:
// ... 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);
}
})
或者,如果您想发送文本,您可以在上传之前对文本进行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);
}
})
答案 1 :(得分:0)
试试这个......
private void upload(object sender, EventArgs e)
{
OAuthUtility.PutAsync
(
"https://content.dropboxapi.com/1/files_put/auto/",
new HttpParameterCollection
{
{"access_token",Properties.Settings.Default.AccessToken},
{ "path", Path.Combine(this.CurrentPath, Path.GetFileName(openFileDialog1.FileName)).Replace("\\", "/") },
{ "overwrite","false"},
{ "autorename","false"},
{openFileDialog1.OpenFile()}
},
callback : Upload_Result
);
}