Node Express sending image files as API response

后端 未结 2 2005
鱼传尺愫
鱼传尺愫 2020-12-08 00:14

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

相关标签:
2条回答
  • 2020-12-08 00:34

    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.

    0 讨论(0)
  • 2020-12-08 00:53

    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

    0 讨论(0)
提交回复
热议问题