首页 > 解决方案 > 将文件流式传输给用户以在 Node/Express 中下载

问题描述

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

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

我正在使用requestnpm 包来调用另一个 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.jsapiexpressstream

解决方案


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

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

您可以从有关流的节点文档中获取有关流管道的更多信息。


推荐阅读