【发布时间】:2015-03-12 12:37:11
【问题描述】:
我正在使用Dropbox Core API 通过 chrome 扩展程序上传和下载文件。当我上传带有扩展名 .txt、.js、.json 或 .c 的文本文件时,文件会成功上传,但是当我上传带有扩展名 .pdf、.jpg 等(媒体文件)的文件时,内容会损坏或不存在,尽管文件大小不为零,有时甚至比原始文件还要大。这显然意味着读取的数据也在写入,但我想我读取或写入数据的方式存在一些问题。代码贴在下面供参考。
$(document).on("click", "#id_submit",uploadProcess);
function uploadProcess()
{
var file = $("#upload_file")[0].files[0];
console.log(file);
if (!file){
alert ("No file selected to upload.");
return false;
}
var reader = new FileReader();
//reader.readAsText(file, "UTF-8");
reader.readAsBinaryString(file);
reader.onload = function (evt) {
uploadFile(file.name, evt.target.result, file.size, file.type);
//console.log(evt.target.result);
var control = $("#upload_file");
control.replaceWith( control = control.clone( true ));
}
}
//function to upload file to folder
function uploadFile(filepath,data,contentLength,contentType){
var url = "https://api-content.dropbox.com/1/files_put/auto/"+filepath;
var headers = {
Authorization: 'Bearer ' + getAccessToken(),
contentLength: contentLength
}
var args = {
url: url,
headers: headers,
crossDomain: true,
crossOrigin: true,
type: 'PUT',
contentType: contentType,
data : data,
dataType: 'json',
success: function(data)
{
console.log(data);
},
error: function(jqXHR)
{
console.log(jqXHR);
}
};
$.ajax(args);
}
【问题讨论】:
-
您总是将 contentType 设置为“text/plain”,这对于您提到的文本文件很好,但不适用于其他文件,请将其替换为您发送给函数的 contentType 变量
-
@juvian 对不起,我在这里发布了旧代码,我已经更正了,现在我在阅读
file.type后传递了内容类型。问题仍然存在。 -
尝试改用 readAsArrayBuffer。如果还是不行,尝试添加 text/plain 的 Accept header; charset=iso-8859-1 并将内容类型设置为文本/纯文本; charset=iso-8859-1
-
@juvian 也不起作用。修改后的代码发布在这里。 jsfiddle.net/x4Lrj67x
-
奇怪,请尝试向 Dropbox 支持发送电子邮件
标签: javascript dropbox dropbox-api filereader