可能是一个愚蠢的问题,但也许有人可以帮助我。
使用multer
上传文件并表达后,上传文件的网址是uploads/
?
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
}
});
如果它是一张图片,我该如何链接到它:
http://localhost:3000/uploads/image.jpg
?
我应该将上传的文件放在公共目录中吗?
感谢
答案 0 :(得分:0)
这就是我为expressjs
设置Multer的方法。首先,如果要保留原始文件名,则必须覆盖重命名功能。然后,您必须将uploads文件夹移动到公用文件夹。
// this uploads a single input[file] field called 'image'
var express = require('express'),
multer = require('multer'),
upload = multer({
storage: multer.diskStorage({
destination: 'public/images/uploads/',
filename: function(req, file, cb) {
// this overwrites the default multer renaming callback
// and simply saves the file as it is
cb(null, file.originalname)
}
})
}),
router = express.Router()
// add route
router.post('/uploadimage', upload.single('image'), function(req, res, next) {
if (!req.file) return next(new Error('Select a file!'))
// be careful here as the upload path has 'public' at the start
// which is the static mounted directory so doesn't show
// here the path is build manually
var imagePath = '/images/uploads/' + req.file.filename;
res.end('<img src=" + imagePath + " />')
})
另外,您可以将默认上传路径保留为/uploads
并将其安装为静态文件夹
// Mount uploads
app.use(express.static(path.resolve('./uploads')));
答案 1 :(得分:0)