这几天写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的参数可见下面的表格, 配置方法见代码
- 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.");
}
});
});