使用Multer和Mongodb上传不同领域的图像

xmjla07d  于 2023-01-20  发布在  Go
关注(0)|答案(2)|浏览(112)

在寻找这个主题的解决方案时,我还没有找到任何与mongodb直接相关的东西,只找到了与multer本身相关的东西。因此,对于我的一个API路由,我希望使用multer上传一个图像,它有多个字段,而不是将它们作为一个数组上传。
这个API的主要功能是抓取图像,将文件保存到本地文件系统,然后将文件名保存到mongodb中,但是我不确定如何处理这个文件名。
当使用这样的代码时,它只返回[Black.jpg]而不是文件名,此外,图像确实以正确的名称显示在FS中
如果可能的话,我希望避免使用.any(),但是我发现的所有解决方案都无法实现
谢谢:))

const storage = multer.diskStorage({
    destination: (req, res, cb) => {
        cb(null, dir)
    },
    filename: (req, file, cb) => {
        cb(null, Date.now() + file.originalname)
    }
})

const upload = multer({
    storage: storage
})

router.post('/', upload.any(), async (req, res) => {
    const business = new Business({
        name: req.body.name,
        type: req.body.type,
        phone: req.body.phone,
        address: req.body.address,
        coverimg: req.file!==undefined ? req.file.filename : 'Black.jpg',
        mainimg: req.file!==undefined ? req.file.filename : 'Black.jpg'
    })
    try {
        const newBusiness = await business.save()
        res.status(201).json(newBusiness)
    } catch (err) {
        res.status(400).json({ message: err.message });
    }
})
gcuhipw9

gcuhipw91#

const storage = multer.diskStorage({
        destination: function(req, res, cb){
            cb(null, './public/**mention folder name here**')
        },
        filename: function(req, file, cb){
          var ext = file.originalname.split(".").pop();
        cb(null, file.fieldname + "-" + Date.now() + "." + ext);
        
        }
      });

This is how the name of the image appears in local fs: 
syntax = field name(sent from frontend)-1673873361364.extention
example =image-1673873361364.jpg

Instead of upload.any() you can use
syntax= upload.single("field name(sent from frontend)")
example=upload.single("single")
jchrr9hc

jchrr9hc2#

是的,我发现当使用upload.fields并通过数组访问它时,我终于可以得到值,下面是如何得到的:D

const storage = multer.diskStorage({
    destination: (req, res, cb) => {
        cb(null, dir)
    },
    filename: (req, file, cb) => {
        cb(null, Date.now() + file.originalname)
    }
})

const upload = multer({
    storage: storage
})

var uploadFields = upload.fields([{name: 'coverimg'}, {name: 'mainimg'}])

router.post('/', uploadFields, async (req, res) => {
    const business = new Business({
        name: req.body.name,
        type: req.body.type,
        phone: req.body.phone,
        address: req.body.address,
        coverimg: req.files['coverimg']!==undefined ? req.files['coverimg'][0]['filename'] : 'Black.jpg',
        mainimg: req.files['mainimg']!==undefined ? req.files['mainimg'][0]['filename'] : 'Black.jpg'
    })
    try {
        const newBusiness = await business.save()
        res.status(201).json(newBusiness)
    } catch (err) {
        res.status(400).json({ message: err.message });
    }
})

冷却:p

相关问题