问题
I am working on a simple chrome-extension that needs to upload files to the user's dropbox folder. I am using the simple AJAX requests as mentioned below to upload files, however it works for files with extensions such as .txt, .json, .c, etc
i.e. files whose mime type
is of type text/plain
or similar type but all other file types such as pdfs, image files etc get corrupted and produce blank contents. What am I missing in uploading the files the correct way.
function startUpload()
{
var folderPath = $(this).closest('tr').attr('path')+'/';
var file = $("#upload_file")[0].files[0];
if (!file){
alert ("No file selected to upload.");
return false;
}
var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function (evt) {
uploadFile(folderPath+file.name,evt.target.result,file.size,file.type);
}
}
//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)
{
getMetadata(filepath.substring(0,filepath.lastIndexOf('/')),createFolderViews);
},
error: function(jqXHR)
{
console.log(jqXHR);
}
};
$.ajax(args);
}
回答1:
I believe the issue is reader.readAsTextFile(file, "UTF-8")
. If the file isn't a text file, this will misinterpret the contents. I think you want reader.readAsBinaryString
or reader.readAsArrayBuffer
. (I haven't tested it myself.)
EDIT
After testing this myself, I found that readAsArrayBuffer
is what you need, but you also need to add processData: false
as an option to $.ajax
to prevent jQuery from trying to convert the data to fields in a form submission.
Also be sure to use dataType: 'json'
to properly parse the response from the server.
来源:https://stackoverflow.com/questions/29288829/upload-files-to-dropbox-using-a-dropbox-core-api-in-javascript