【问题标题】:Inconsistent file contents on uploading through Dropbox API通过 Dropbox API 上传的文件内容不一致
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 我知道我们可以在 ajax 请求中传递一个文件,但这与 dropbox api 规范不一致。
  • @bawejakunal 我没有看到任何不一致之处。你试过了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-13
  • 1970-01-01
  • 2016-03-13
相关资源
最近更新 更多