如何在Node.js multer图片上传中定义静态文件夹路径

时间:2019-11-28 08:22:58

标签: node.js mongodb multer

我正在设置静态路径,但出现错误:“错误:ENOENT:没有此类文件或目录,请打开'C:\ dashboard new-Copy \ uploads \ 2019-11-28T08:11:09.164Z1564660431900.jpg'“ < / p>

const storage = multer.diskStorage({  destination: function(req, file, cb) { let dest = path.join(__dirname, '../../uploads'); cb(null, dest);  }, filename: function(req, file, cb) {    cb(null, new Date().toISOString() + file.originalname);  }});

const fileFilter = (req, file, cb) => {  if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {    cb(null, true);  } else {    cb(null, false);  }};

const upload = multer({  storage: storage,  limits: {    fileSize: 1024 * 1024 * 5  }, fileFilter: fileFilter});

router.post("/", upload.single('productImage'), async (req, res, next) => {
try {
    cosole.log('hi');
    const product = new Product({
      _id: new mongoose.Types.ObjectId(),
      name: req.body.name,
      price: req.body.price,
      productImage: req.file.path 
    });
    const saveImage = await product.save();
    console.log(saveImage)
    res.json(saveImage);
} catch (error) {
  console.log(error);
  res.json(error);
}

});

该怎么做?

1 个答案:

答案 0 :(得分:1)

我认为您需要提供目标文件夹作为键和值,如下所示(

var upload = multer({dest:'uploads /'})

您可以在此处查看完整的multer文档 https://expressjs.com/en/resources/middleware/multer.html