Image Node Express将图像文件作为API响应发送

Image Node Express将图像文件作为API响应发送,image,node.js,express,Image,Node.js,Express,我在谷歌上搜索了这个问题,但找不到答案,但这肯定是一个常见问题。这是与相同的问题,但尚未回答 如何将图像文件作为Express.send()响应发送?我需要将RESTful URL映射到图像,但是如何发送具有正确标题的二进制文件呢?例如: <img src='/report/378334e22/e33423222' /> Express中有一个api res.sendFile app.get('/report/:chart_id/:user_id', function (req,

我在谷歌上搜索了这个问题,但找不到答案,但这肯定是一个常见问题。这是与相同的问题,但尚未回答

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

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

Express中有一个api

res.sendFile

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

下面是一个包含流和错误处理的适当解决方案:

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
})
const fs=require('fs'))
const stream=require('stream')
app.get('/report/:chart\u id/:user\u id',(req,res)=>{
const r=fs.createReadStream('path to file')//或获取可读流的任何其他方法

const ps=new stream.PassThrough()//如何检索图像服务器端?可以从流中检索而不是文件路径吗?例如,如果您有一个变量将文件存储在其中,这样您就不必实际将文件保存在服务器上?@BRogers
res
是一个可写流,因此如果您有一个
缓冲区
对象或
字符串
t然后你可以使用
.write
方法将其发送到客户端。谢谢,我将尝试此方法。我有一个CSV缓冲区,我想发送回客户端,并显示为下载的文件。我将不得不玩弄它。该文件不是很大,所以我希望能够完成此操作。这非常有效!只需记住设置
内容nt类型
。谢谢!res.sendfile现在已被弃用,首选方法是res.sendfile:
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
})