我使用的是Express 4.13,在尝试服务文件时遇到了一些问题:
function doServeFile(name, fullpath, res, download) {
if (fullpath) {
if (download)
res.download(fullpath, name);
else {
res.sendFile(fullpath, {}, function (err) {
console.info(err);
});
}
}
else {
res.status(404);
}
}
function serveFile(id, res, download) {
Model.findById(id).then(file=> {
var fullPath = Config.uploadDest + "/" + file.path;
doServeFile(file.filename, fullPath, res, download)
}).catch(Util.dbErrorHandler);
}
router.get("/:id", function (req, res, next) {
serveFile(req.params.id, res);
});
router.get("/download/:id", function (req, res, next) {
serveFile(req.params.id, res, true);
});如代码所示,一旦我向服务器发送请求/1,它将检索id为1的文件以获取文件路径,然后使用res.sendFile将该文件提供给客户端。
但是,当我运行应用程序时,我发现请求将挂起太长时间,无法获得响应。但是我可以看到这样的日志:
---try send file:D:/file_upload/1464578330791_user.jpg
似乎已经获取了文件,但是res.sendFile没有完成它的工作。
此外,当我尝试使用/download/1时,可以下载该文件。
怎么回事?
发布于 2016-05-30 17:29:19
前几天我遇到了同样的问题,发现sendFile实际上并没有正确地识别绝对路径,并且挂起了。设置root选项解决了此问题。希望它能为你工作。
res.sendFile(fullpath, {root: '/'});发布于 2016-05-31 09:46:14
在深入研究了express的源代码之后,我找到了答案。
当调用res.sendFile时,express将确保设置了路径的root或路径必须是绝对路径,请检查this,导致此问题的正是isAbsolutepath codes
exports.isAbsolute = function(path){
if ('/' == path[0]) return true;
if (':' == path[1] && '\\' == path[2]) return true;
if ('\\\\' == path.substring(0, 2)) return true; // Microsoft Azure absolute path
};所以像这样的路径
D:/a/a.txt不会被视为绝对路径!
D:\\a\\a.txt将会是。类似linux的path /home/a/a.txt也是如此。
这就是我如何构建路径(手动),从express的角度来看,这不是绝对路径:
var fullPath = Config.uploadDest + "/" + file.path;因此,我将其更改为:
var fullPath = path.join(Config.uploadDest,file.path);啊,真灵。
发布于 2017-04-21 20:12:06
如果您使用的是windows操作系统,请使用其完整路径,如
D:/folder1/folder2/index.html
https://stackoverflow.com/questions/37521185
复制相似问题