使用multer上传图片

时间:2021-03-01 09:46:27

标签: node.js mongoose multer

这是我的代码我必须在显示图像中放置3张图像,显示图像和显示徽标..怎么做?

const createStore = async (req,res,next) => {
    var id = req.params.tempid;
    var tempDetail = await Template.findById({_id:id})
    console.log("create store running,,,,,,,")
      var store={
        "store_id":req.body.store_id,
        "store_name":req.body.store_name,
        "context": req.body.context,
        "display_image": req.files,
        "display_images":req.files,
        "display_logo":req.files
        
        
    }
    console.log("before store save")
    console.log(req.files)
    try{
      await Template.updateOne(
        { _id: id },
        { $push: { store:store }}
    )

    res.status(200).json({
        
        message:"store added successfully",
        result:store
        

    })

这是路由 :- router.post("/createStore/:tempid",verifyUser,upload.array('display_image display_images display_logo',maxCount=10), templateController.createStore)

1 个答案:

答案 0 :(得分:0)

我假设 display image,display images and display logo 在不同的领域。所以你可以使用 multer fields

multer 中间件

upload.fields([
    {
        name: 'display_image', maxCount: 1
    },
    {
        name: 'display_images', maxCount: 1
    }, 
    {
        name: 'display_logo', maxCount: 1
    }
])

控制器

const display_image = req.files && req.files.display_image ? req.files.display_image[0] : undefined;
    const display_images = req.files && req.files.display_images ? req.files.display_images[0] : undefined;
    const display_logo = req.files && req.files.display_logo ? req.files.display_logo[0] : undefined;