URL 到使用 Multer 上传的文件
URL to file which was uploaded with Multer
我正在使用 Multer 上传一些文件,我想知道上传后访问这些文件的推荐方式是什么。
这是我的代码:
server.js
app.use('/', require('./routes'));
routes/index.js
var teacher = require('./teachers.js');
router.post('/upload', teacher.uploadAvatar);
routes/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");
});
}
访问以下 Url localhost:8000/uploads/teacher/uploaded_file_name.png
给出错误 Error: Not Found
.
您需要为 static
项资产(包括上传)创建一个 public
文件夹。因此您的文件夹结构将类似于 ./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
我正在使用 Multer 上传一些文件,我想知道上传后访问这些文件的推荐方式是什么。
这是我的代码:
server.js
app.use('/', require('./routes'));
routes/index.js
var teacher = require('./teachers.js');
router.post('/upload', teacher.uploadAvatar);
routes/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");
});
}
访问以下 Url localhost:8000/uploads/teacher/uploaded_file_name.png
给出错误 Error: Not Found
.
您需要为 static
项资产(包括上传)创建一个 public
文件夹。因此您的文件夹结构将类似于 ./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