Nodejs实现图片上传,链接保存到Mongodb数据库

2022-01-24 08:53:15 浏览数 (2)

需求: 客户端批量上传图片到服务器,服务器返回图片链接

用到的主要工具及node库有 multer mongoose

代码如下

代码语言:javascript复制
var router = require('express').Router()
var projectInfo = require('../projectInfo.json')
var multer = require('multer')
let PictureStore = require(PROXY).pictureStore

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './public/upload')
  },
  filename: function (req, file, cb) {
    var str = file.originalname.split('.')
    cb(null, Date.now()   '.'   str[1])
  }
})
var upload = multer({storage: storage})

// 上传图片到图片仓库并返回上传的图片路径
router.post('/uploadImgs', upload.array('file', 20), function (req, res, next) {
  var arr = []
  for (var i in req.files) {
    arr.push(global.SERVICEADDRESS   ''   req.files[i].filename)
  }
  if (req.body.storeId) {
    PictureStore.updateOnePictureStore({_id: req.body.storeId}, {$addToSet: {pictureUrlArr: {$each: arr}}}, (err, data) => {
      res.json({
        code: 200,
        data: arr
      })
    })
  } else {
    PictureStore.updateOnePictureStore({isCommon: true}, {$addToSet: {pictureUrlArr: {$each: arr}}}, (err, data) => {
      res.json({
        code: 200,
        data: arr
      })
    })
  }
})

上传图片到服务器的public/upload文件夹下

更新图片链接到图片库, 主要是用了

代码语言:javascript复制
{$addToSet: {pictureUrlArr: {$each: arr}}}  批量插入一个数组

0 人点赞