首页 > 解决方案 > 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什么的。当我将图像移动到项目的子文件夹时,图像不会以某种方式发送。

你能帮我吗?

标签: express

解决方案


要解决此类问题,您只需要进行一些调试即可。

首先,添加这个:

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);

它将尝试使用完整路径发送它(根本不使用根设置)。如果即使这样也不起作用,那么该文件一定不在您认为的位置,或者您没有正确的权限来查看或读取它。


推荐阅读