Stream files in node/express to client

前端 未结 2 837
萌比男神i
萌比男神i 2020-12-08 02:10

I want to stream content to clients which is possibly stored in db, which they would save as files.

Obviously res.download would do the job nicely, but none of the r

相关标签:
2条回答
  • 2020-12-08 02:40

    You can stream directly to the response object (it is a Stream).

    A basic file stream would look something like this.

    function(req, res, next) {
      if(req.url==="somethingorAnother") {
        res.setHeader("content-type", "some/type");
        fs.createReadStream("./toSomeFile").pipe(res);
      } else {
        next(); // not our concern, pass along to next middleware function
      }
    }
    

    This will take care of binding to data and end events.

    0 讨论(0)
  • 2020-12-08 02:54

    Make sure that your AJAX request from the client has an appropriate 'responseType' set. for example like

    $http({
      method :'GET',
      url : http://url,
      params:{},
      responseType: 'arraybuffer'
    }).success()
    
    0 讨论(0)
提交回复
热议问题