我有image collection
以下架构:
{
"productId": {type: String},
"imagePaths": {type: Array}
}
我想上传多个图片并将相应的image-paths
存储到数据库中。
我搜索了一下,并且知道Multer
可以执行此操作,但我无法上传和保存多个图像的图像路径。
我试过这个Angular代码,
scope.demoMethod = function(){
console.log('Method fired.');
var product = $scope.product;
$http.post('/demo/upload', $scope.product)
.then(function (res) {
console.log('Form Data ::' + $scope.product);
});
},
但是我收到错误,无法读取未定义的属性'forEach'
答案 0 :(得分:0)
首先,您需要定义磁盘存储,即保存文件的位置
<use>
然后在您的路线中添加multer作为中间件
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, `${global.uploadDir}/temp`); // folder path
},
filename: (req, file, cb) => {
cb(null, `${uuid()}.${mime.extension(file.mimetype)}`); // file name here
}
});
multer = multer({ storage });
您也可以指定文件&#39;过滤
router.post('/upload', multer.any(), (req, res) => {
console.log(req.files) // should be array of files you have uploaded
const imagePaths = [];
req.files.forEach(f => {
imagePaths.push(f.path);
});
const product = new Product(); // model name
product.imagePaths = imagePaths;
...
product.save();
...
});
并限制
const fileFilter = (req, file, cb) => {
const isAllowed = utils.isAllowed(mime.extension(file.mimetype)); // your validation condition here
if (!isAllowed) {
return cb(new Error('This file is not allowed'));
}
cb(null, true);
}
multer = multer({ storage, fileFilter });