【问题标题】:Stream file to user for download in Node/Express将文件流式传输给用户以在 Node/Express 中下载
【发布时间】:2018-07-15 10:36:00
【问题描述】:

我想就 Node / Express 中的 REST API 向您寻求帮助。

我正在调用供应商 API 以获取 PDF 格式的标签,然后我需要将其发送给正在调用 API 的用户。

我正在使用request npm 包调用另一个 API。我也尝试过node-fetch,但没有成功。

示例代码:

retrieveLabel(req, res, next) {
  const options = {
    method: 'GET',
    url: 'apiUrl' + 'shipments/xxx/label',
    headers: {
      'cache-control': 'no-cache',
      authorization: xxxToken,
      'content-type': 'application/json'
    }
  };
  request(options, (error, response, results) => {
    // NO idea how to send it as reponse...


  });
}

在控制台中有字符串类型的响应,以这样的开头:

%PDF-1.4
%����
3 0 obj
<
</Type /XObject /Subtype /Image /Width 1171 /Height 1676 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Decode [0 1 0 1 0 1] /Interpolate false /Filter /FlateDecode /DecodeParms<
</Predictor 12 /Colors 3 /Columns 1171 >>
 /Length 61782 >>
stream
X���o�]�}'�;!Yl"�ɠh����x�H&�r�h�@(�3[ҋHK"�r+)K�q{kYL���fl���H�)��@�By�v�Ԭ\Z��3�-�5�Զ*PEJ���EU�����G�Ϲ�v���t��S��n���s�sn��>�y���1y��y��r'��Nrȝ��;�
 wݓ�Ν;�m��b�X,��b�X,s�D �MO?�܊,6@rK&''w����b���266�H�%��_~��r�C���X,�e�K��������U��۲e���%+�������|���*��?pr �@�$7��In���r'��Nrȝ�0���o���|עʑ#Gn�������u�s��Z���ɓqe��|U >��9z�%�ٳw
....

【问题讨论】:

    标签: node.js api express stream


    【解决方案1】:

    API 中的response 是可读流。您的 res(来自您的网站客户端的 http 请求)是一个可写流。实现目标的最简单方法是将可读流通过管道传输到可写流中,如下所示:

    retrieveLabel(req, res, next) {
        //...
        request(options, (error, response, results) => {
            response.pipe(res);
        });
        //...
    

    您可以通过流上的node documentation 获取有关流管道的更多信息。

    【讨论】:

    • 嗨,大卫,感谢您的回答,但我仍然无法得到它。我尝试使用fs.createWriteStream、response.pipe(res) 以及添加到标题“application/pdf”类型,但没有运气。使用管道,我收到错误 -> TypeError: dest.end is not a function
    • 嗨,大卫,我还发现了一些请求 npm 包的示例 -> request(options) .on('error', (err) =&gt; { console.log('error', err) }) .pipe(fs.createWriteStream('Label.pdf')) .on('finish', (response) =&gt; { console.log('success', response); return res.send({ error: false, message: 'success' }); }); 这几乎是我想要的,但是文件正在保存在 API 目标上......它没有要求用户保存它.
    猜你喜欢
    • 2017-04-02
    • 1970-01-01
    • 1970-01-01
    • 2011-01-18
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多