node.js - 将文件流式传输给用户以在 Node/Express 中下载
问题描述
我想就 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
....
解决方案
你response
的 API 是一个可读的流。您的res
(对来自您网站客户端的 http 请求的响应)是一个可写流。实现目标的最简单方法是将可读流通过管道传输到可写流中,如下所示:
retrieveLabel(req, res, next) {
//...
request(options, (error, response, results) => {
response.pipe(res);
});
//...
您可以从有关流的节点文档中获取有关流管道的更多信息。
推荐阅读
- flutter - Flutter 应用中提供程序与 sqflite 的集成
- php - 代码不会创建正确的 HMAC-SHA256 签名
- google-api - Google 智能设备管理 API 调用中缺少恒温器设备
- list - 拼接列表中的子列表,不使用 flatten/2
- vb.net - 当两个表单都处于活动状态时,如何在 VB.NET 的另一个表单中更新标签中的文本(消息传递)[Visual Studio 2010]
- c - 如何解决这个关于 C 中序列的问题?
- deep-learning - 为什么深度自适应输入归一化 (DAIN) 对跨行的时间序列数据进行归一化?
- visual-studio - MSBuild 和 VS2019 参考解决差异
- java - 为什么哦为什么,我的 scrollPane 不能滚动到任何地方?
- jquery - 如何动态添加 enctype="multipart/form-data" 到表单?