node.js Node Express 发送图像文件作为 API 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17515699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:58:08  来源:igfitidea点击:

Node Express sending image files as API response

imagenode.jsexpress

提问by metalaureate

I Googled this but couldn't find an answer but it must be a common problem. This is the same question as Node request (read image stream - pipe back to response), which is unanswered.

我用谷歌搜索了这个,但找不到答案,但这一定是一个常见问题。这是与Node request (read image stream - pipe back to response)相同的问题,没有回答。

How do I send an image file as an Express .send() response? I need to map RESTful urls to images - but how do I send the binary file with the right headers? E.g.,

如何将图像文件作为 Express .send() 响应发送?我需要将 RESTful url 映射到图像 - 但是如何发送带有正确标题的二进制文件?例如,

<img src='/report/378334e22/e33423222' />

Calls...

打电话...

app.get('/report/:chart_id/:user_id', function (req, res) {
     //authenticate user_id, get chart_id obfuscated url
     //send image binary with correct headers
});

回答by Po-Ying Chen

There is an api in Express.

Express中有一个api。

res.sendFile

res.sendFile

app.get('/report/:chart_id/:user_id', function (req, res) {
    // res.sendFile(filepath);
});

http://expressjs.com/en/api.html#res.sendFile

http://expressjs.com/en/api.html#res.sendFile

回答by kharandziuk

a proper solution with streams and error handling is below:

流和错误处理的正确解决方案如下:

const fs = require('fs')
const stream = require('stream')

app.get('/report/:chart_id/:user_id',(req, res) => {
  const r = fs.createReadStream('path to file') // or any other way to get a readable stream
  const ps = new stream.PassThrough() // <---- this makes a trick with stream error handling
  stream.pipeline(
   r,
   ps, // <---- this makes a trick with stream error handling
   (err) => {
    if (err) {
      console.log(err) // No such file or any other kind of error
      return res.sendStatus(400); 
    }
  })
  ps.pipe(res) // <---- this makes a trick with stream error handling
})

with Node older then 10 you will need to use pumpinstead of pipeline.

如果节点比 10 旧,您将需要使用而不是管道。