【发布时间】:2018-10-04 06:02:00
【问题描述】:
我有一个使用 node.js、express 和 multer 上传文件的系统,文件存储在静态目录中。我想要的是将它们存储在服务器上,并且只有在我登录后才能看到它们。
问题:
我的上传系统很好,但我需要保护目录 /files/documents/hv.pdf 中的文件,因为每当我输入打开文件的 url 时,浏览器都会保存历史记录,这是不应该发生的事情,如果用户没有登录,如何避免访问?
我正在尝试使用一个中间件,如果 url 的字符串带有 /files 文件夹的名称,它会运行,有趣的是,如果我不输入文件名或输入另一个名称,如 /files/document/test.txt 它可以工作但不是当我访问静态文件夹中的链接时,我以为是缓存但绝对不是那个
这个中间件
module.exports = (req,res,next)=>{
let regex = /^\/files\/.*$/;
if (!regex.test(req.url)) { return next(); }
// for test
req.session.user = {name:"thaylor"}; //comment for not session
//fin for test
if(req.session.user){
next();
}else{
res.end('You are not allowed!');
}
}
更新,这个解决方案 2018-04-2017
获取根路径和受保护路由 app.js 的中间件
const protectedfile = require("./controllers/protectedfile");
app.use(function(req, res, next) {
req.rootPath = __dirname;
next();
});
app.use('/files', protectedfile);
app.use('/files', express.static(path.join(__dirname, 'files')) );
这个文件控制器/protectedfile.js
const path = require('path');
module.exports = (req,res,next)=>{
if(!req.session.user){
res.send("Route protected");
}else{
let file = path.join(req.rootPath, req.originalUrl);
res.download(file, function (err) {
if (err) {
console.log("Error");
console.log(err);
} else {
console.log("success");
}
});
}
}
谢谢大家
【问题讨论】:
-
当然不会,static 文件夹是......好吧应该是静态的。也就是说您不想将文件上传到您的静态文件夹(通常命名为
public。您可以创建一个名为upload的文件夹并设置app.set('upload', uloade_path)并用作req.app.get('upload')。 -
我不明白你的解决方案
-
下面看我的详细解释。希望能解决您的问题:)
标签: node.js express directory protected multer