express-sendfilefrom子目录
我有一个小的express应用程序,我想在其中发送一个图像文件 这项工作:express-sendfilefrom子目录,express,Express,我有一个小的express应用程序,我想在其中发送一个图像文件 这项工作: const options = { root: __dirname, dotfiles: 'deny' }; res.sendFile(`${req.params.articleId}.png`, options); 这是行不通的: const options = { root: __dirname + '/images, dotfiles: 'deny' }; res.sendFi
const options = {
root: __dirname,
dotfiles: 'deny'
};
res.sendFile(`${req.params.articleId}.png`, options);
这是行不通的:
const options = {
root: __dirname + '/images,
dotfiles: 'deny'
};
res.sendFile(`${req.params.articleId}.png`, options);
即使使用path.resolve
或其他方法。不知何故,当我将图像移动到项目的子文件夹时,图像没有被发送
你能帮我吗?要解决这样的问题,你只需要做一些调试 首先,添加以下内容:
const rootDir = path.join(__dirname, "images");
console.log(rootDir);
const options = {
root: rootDir,
dotfiles: 'deny'
};
const filename = `${req.params.articleId}.png`;
console.log(filename);
res.sendFile(filename, options);
const filename = `${req.params.articleId}.png`;
console.log(filename);
const fullname = path.join(rootDir, filename);
console.log(`${fullname} exists: ${fs.existsSync(fullname)}`);
res.sendFile(filename, options);
并且,验证rootDir
和filename
确实是您想要的目录和文件名
如果仍然不起作用,则添加以下内容:
const rootDir = path.join(__dirname, "images");
console.log(rootDir);
const options = {
root: rootDir,
dotfiles: 'deny'
};
const filename = `${req.params.articleId}.png`;
console.log(filename);
res.sendFile(filename, options);
const filename = `${req.params.articleId}.png`;
console.log(filename);
const fullname = path.join(rootDir, filename);
console.log(`${fullname} exists: ${fs.existsSync(fullname)}`);
res.sendFile(filename, options);
如果这并没有显示fullname存在,那么请三次检查您的文件路径,并确保文件确实存在。检查文件权限 如果全名存在,但
res.sendFile()
仍不起作用,请尝试以下操作:
const filename = `${req.params.articleId}.png`;
const fullname = path.join(rootDir, filename);
res.sendFile(fullname, options);
它将尝试使用完整路径发送它(根本不使用root设置)。如果即使这样也不起作用,那么该文件也不能位于您认为的位置,或者您没有查看或读取该文件的正确权限。requ.params.articleId的确切值是多少?
\uu dirname
的确切值是多少?这是图像的父目录吗?你在哪个站台上跑步?您是否尝试过:root:path.join(\uu dirname,'images'),
?还有,images
目录是否在该模块所在目录的正下方?@johnbraum-这是否回答了您的问题?如果是这样的话,您可以通过单击答案左侧的复选标记向社区表明这一点,这也将为您赢得一些遵守正确程序的声誉积分。