节点快速发送图像文件作为 API 响应

我在谷歌上搜索了一下,但是没有找到答案,但是这一定是一个普遍的问题。这个问题和 节点请求(将图像流管道读回响应)一样,没有答案。

如何将图像文件作为 Express 发送。发送()响应?我需要映射 RESTful 网址到图像-但是我如何发送带有正确头的二进制文件?例如:

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

电话..。

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

There is an api in Express.

res.sendFile

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

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

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 pump instead of pipeline.