如何使用Multer将图像保存到文件夹并将imagePath保存到MEAN堆栈中的数据库

时间:2017-09-02 13:53:02

标签: angularjs node.js mongodb express multer

我有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'

1 个答案:

答案 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 });