使用Javascript中的Dropbox Core API将文件上载到Dropbox

Upload files to Dropbox using a Dropbox Core API in Javascript

本文关键字:Dropbox 文件 上载 Core Javascript 中的 使用 API      更新时间:2023-09-26

我正在开发一个简单的chrome扩展,它需要将文件上传到用户的dropbox文件夹。我使用下面提到的简单AJAX请求上传文件,但它适用于扩展名为.txt, .json, .c, etc的文件,即mime typetext/plain或类似类型的文件,但所有其他文件类型(如PDF、图像文件等)都会损坏并产生空白内容。以正确的方式上传文件我缺少什么。

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);
}

我认为问题出在reader.readAsTextFile(file, "UTF-8")上。如果该文件不是文本文件,则会误解内容。我认为您想要reader.readAsBinaryStringreader.readAsArrayBuffer。(我自己还没有测试过。)

编辑

经过自己的测试,我发现readAsArrayBuffer正是您所需要的,但您还需要将processData: false作为选项添加到$.ajax中,以防止jQuery试图将数据转换为表单提交中的字段。

还要确保使用dataType: 'json'正确解析来自服务器的响应。