我正在使用Multer上传一些文件,我想知道上传后访问这些文件的推荐方法是什么。
这是我的代码:
server.js
app.use('/', require('./routes'));
路由/ index.js
var teacher = require('./teachers.js');
router.post('/upload', teacher.uploadAvatar);
路由/ teachers.js
var multer = require('multer');
var upload = multer({ dest: 'uploads/teacher/' }).single('avatar');
uploadAvatar: function(req, res) {
upload(req, res, function(err) {
console.log(req.body);
console.log(req.file);
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
}
访问以下网址localhost:8000/uploads/teacher/uploaded_file_name.png
会出现错误Error: Not Found
。
答案 0 :(得分:2)
您需要为public
资产(包括上传)创建static
文件夹。因此,您的文件夹结构将显示为./public/uploads/teacher/
。
然后,您必须更新routes/teachers.js
中的以下行:
var upload = multer({ dest: 'uploads/teacher/' }).single('avatar');
为:
var upload = multer({ dest: 'public/uploads/teacher/' }).single('avatar');
并将以下行添加到server.js
以提供public
目录中的静态资源:
app.use(express.static('public'));
然后,您应该可以访问localhost:8000/uploads/teacher/uploaded_file_name.png