express - express - 从子目录发送文件
问题描述
我有一个小型快递应用程序,我想在其中发送图像文件。
这有效:
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);
并且,验证rootDir
并且filename
确实是您希望它们成为的目录和文件名。
如果这仍然不起作用,请添加以下内容:
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 存在,则三重检查您的文件路径并确保该文件确实存在。检查文件权限。
如果 fullname 存在,但res.sendFile()
仍然不起作用,请尝试以下操作:
const filename = `${req.params.articleId}.png`;
const fullname = path.join(rootDir, filename);
res.sendFile(fullname, options);
它将尝试使用完整路径发送它(根本不使用根设置)。如果即使这样也不起作用,那么该文件一定不在您认为的位置,或者您没有正确的权限来查看或读取它。
推荐阅读
- python - 模拟选举
- javascript - 如何通过'的第一个实例拆分字符串
'
- excel - Excel 公式 - 每 6 天获取每个变量的总和
- powershell - Get-WindowsFeatures:如何过滤显示名称?
- spring-boot - 在 Heroku 上部署 JHipster 应用程序时,“无法将 '' 下的属性绑定到 com.zaxxer.hikari.HikariDataSource”
- jquery - 如何销毁 FooTable 实例
- mysql - 如何在 SQL 查询中使用公式并对该结果进行排序
- reactjs - React 测试库 TypeError:无法在“EventTarget”上执行“removeEventListener”:需要 2 个参数,但只有 1 个存在
- sql - 如何删除超过 6 个月大的行,但使用 SQL 确保表中至少有 100 行?
- docker - 在 Spacy 中下载语言模型会在 docker 中中断