【问题标题】:Nodejs - Download a PDF with Dropbox Core API and save to diskNodejs - 使用 Dropbox Core API 下载 PDF 并保存到磁盘
【发布时间】:2015-04-10 11:34:11
【问题描述】:

在使用 Python 和来自 Dropbox 的 Python SDK 之前,我已经成功地做到了这一点,但现在我使用的是 Nodejs 和 Dropbox HTTP API,出现了问题。当我在本地保存 PDF 文件时,我只能看到原始 PDF 的一部分,当我将其与原始文件进行比较时,例如 WinMerge,我发现文件不相等并且大小不同。我能想到的唯一区别是它可能会使用与原始编码不同的编码进行保存,但我已经使用 iconv-lite 尝试了其中的大多数,但没有一个能给出好的结果。

我还尝试使用https://github.com/dropbox/dropbox-js 来查看它是否给出了不同的结果,还尝试使用https://www.npmjs.com/package/request 代替node-rest-client,但没有成功。

有没有人实现过这个并让它工作?

这是我的代码:

var fs = require('fs'),
    RestClient = require('node-rest-client').Client;

var args = {
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/pdf',
        'Authorization': 'Bearer xxx'
    }
};

var restClient = new RestClient();
var url = 'https://api-content.dropbox.com/1/files/auto/' + dropboxPath;
var filePath = '/var/temp/' + fileName;

restClient.get(url, arguments, function(body, response) {
    fs.writeFile(filePath, response, function (error, written, buffer) {});
}

当使用不同的编码进行测试时,它看起来像这样:

var fs = require('fs'),
    RestClient = require('node-rest-client').Client,
    iconvlite = require('iconv-lite');

iconvlite.extendNodeEncodings();

var args = {
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/pdf',
        'Authorization': 'Bearer xxx'
    }
};

var restClient = new RestClient();
var url = 'https://api-content.dropbox.com/1/files/auto/' + dropboxPath;
var filePath = '/var/temp/' + fileName;
var options = { encoding: 'UTF-8' };

restClient.get(url, arguments, function(body, response) {
    fs.writeFile(filePath, response, options, function (error, written, buffer) {});
}

【问题讨论】:

    标签: node.js pdf encoding dropbox-api


    【解决方案1】:

    我认为 node-rest-client 总是将返回的数据转换为字符串,因此最终会损坏二进制数据。见https://github.com/aacerox/node-rest-client/blob/master/lib/node-rest-client.js#L396

    请求库在使用回调时似乎也有类似的问题,但您可以通过管道直接连接到文件来绕过它:

    var fs = require('fs'),
        request = require('request');
    
    var accessToken = '123xyz456';
    var filename = 'myfile.pdf';
    
    request('https://api-content.dropbox.com/1/files/auto/' + filename, {
        auth: { bearer: accessToken }
    }).pipe(fs.createWriteStream(filename));
    

    编辑:我在 GitHub 上针对 node-rest-client 问题提交了一个问题,看起来库维护者已经准备好修复(在一个分支中)。见https://github.com/aacerox/node-rest-client/issues/72

    【讨论】:

    • 哇,非常感谢!我已经花了很多时间来解决这个问题!实际上,我之前也尝试过请求,但不是通过管道传输,以“正常”方式进行操作会产生相同的错误。非常感谢!
    • @missemisa 另请参阅我的编辑。 node-rest-client 维护者现在正在测试修复。
    猜你喜欢
    • 2020-12-17
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    相关资源
    最近更新 更多