通过 Dropbox API 上传时的文件内容不一致

Inconsistent file contents on uploading through Dropbox API

本文关键字:文件 不一致 Dropbox API 通过      更新时间:2023-09-26

我正在使用 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);
}

您实际上可以在 ajax 请求中传递文件(取决于浏览器支持)。只需传递args对象中的文件,还需要将processDate和contentType设置为false,以防止$.ajax操作文件对象

var args = {
    ...
    contentType: false,
    data : file,
    processData: false,
    ...
};