這幾天寫demo的時候想用到網易云音樂的數據, 在github找到了API,里面用的是express+http。我一直對Express不是很熟悉, 在看API的過程中發現res.send要發送一整個網頁文件比較難。于是四處找找找到了sendfile這個方法,這邊簡單寫一篇總結
基于Express 4.x 官方API
參考鏈接 http://expressjs.com/en/4x/api.html#res.sendFile
- Transfers the file at the given path.
- Sets the Content-Type response HTTP header field based on the filename’s extension.
- Unless the root option is set in the options object, path must be an absolute path to the file.
-
option的參數可見下面的表格, 配置方法見代碼
option - 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.");
}
});
});