Express的res.sendfile方法

這幾天寫demo的時候想用到網(wǎng)易云音樂的數(shù)據(jù), 在github找到了API,里面用的是express+http。我一直對Express不是很熟悉, 在看API的過程中發(fā)現(xiàn)res.send要發(fā)送一整個網(wǎng)頁文件比較難。于是四處找找找到了sendfile這個方法,這邊簡單寫一篇總結(jié)

基于Express 4.x 官方API
參考鏈接 http://expressjs.com/en/4x/api.html#res.sendFile

  1. Transfers the file at the given path.
  2. Sets the Content-Type response HTTP header field based on the filename’s extension.
  3. Unless the root option is set in the options object, path must be an absolute path to the file.
  4. option的參數(shù)可見下面的表格, 配置方法見代碼


    option
  5. The method invokes the callback function fn(err) when the transfer is complete or when an error occurs. If the callback function is specified and an error occurs, the callback function must explicitly handle the response process either by ending the request-response cycle, or by passing control to the next route.

Here is an example of using res.sendFile with all its arguments.

app.get('/file/:name', function (req, res, next) {

  var options = {
    root: __dirname + '/public/',
    dotfiles: 'deny',
    headers: {
        'x-timestamp': Date.now(),
        'x-sent': true
    }
  };

  var fileName = req.params.name;
  res.sendFile(fileName, options, function (err) {
    if (err) {
      next(err);
    } else {
      console.log('Sent:', fileName);
    }
  });

});

The following example illustrates using res.sendFile to provide fine-grained support for serving files:

app.get('/user/:uid/photos/:file', function(req, res){
  var uid = req.params.uid
    , file = req.params.file;

  req.user.mayViewFilesFrom(uid, function(yes){
    if (yes) {
      res.sendFile('/uploads/' + uid + '/' + file);
    } else {
      res.status(403).send("Sorry! You can't see that.");
    }
  });
});
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容