【问题标题】:Node Express sending image files as API responseNode Express 发送图像文件作为 API 响应
【发布时间】:2013-07-05 03:21:13
【问题描述】:

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

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

<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
});

【问题讨论】:

  • 如何检索图片服务器端?

标签: image node.js express


【解决方案1】:

Express中有一个api。

res.sendFile

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

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

【讨论】:

  • 你可以从流中代替文件路径吗?例如,如果您有一个用于存储文件的变量,这样您就不必将文件实际保存在服务器上?
  • @BRogers res 是一个可写流,所以如果你有一个Buffer 对象或string 那么你可以使用.write 方法将它发送给客户端。
  • 谢谢,我会试试这个。我有一个 CSV 缓冲区,我想将其发送回客户端,并显示为下载的文件。我将不得不玩弄那个。文件不是很大,所以我希望能做到这一点。
  • 效果很好!只需要记住设置Content-Type。谢谢!
  • res.sendfile 现在已弃用,首选方法是 res.sendFile: expressjs.com/api.html#res.sendFile
【解决方案2】:

流和错误处理的适当解决方案如下:

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
})

如果节点早于 10,您将需要使用 pump 而不是管道。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 2012-04-20
    相关资源
    最近更新 更多