我有一个使用node.js,express和multer上传文件的系统,文件存储在静态目录中。我希望它们存储在服务器上,并且只能在登录后才能查看。
问题:
我的上传系统很好,但是我需要保护目录/files/documents/hv.pdf中的文件,因为当我输入URL时,浏览器会保存历史记录并打开该文件,这是不应该发生的,如何避免用户未登录访问?
我尝试使用一个中间件来运行如果url字符串包含/files文件夹的名称,但很奇怪,如果我不放置文件名或者放置其他名称,例如/files/document/test.txt,它可以工作,但是当我访问静态文件夹中的链接时就不行了,我认为这是缓存,但绝对不是那样
这个中间件
这个文件位于controllers/protectedfile.js。
问题:
我的上传系统很好,但是我需要保护目录/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')) );
这个文件位于controllers/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");
}
});
}
}
public
)。您可以创建一个名为upload
的文件夹,并设置app.set('upload', upload_path)
,并使用req.app.get('upload')
。 - Leo Li