我试图通过数据和缓冲区使用Multer和猫鼬存储图像

时间:2019-01-06 06:54:16

标签: javascript node.js mongodb mongoose multer

我的架构如下

const RecipeSchema = mongoose.Schema({
  user: [
    {
      userName: { type: String, required: true },
      userID: { type: String, required: true },
      userPicture: { data: Buffer, type: String, required: true }
    }
  ],
  recipeName: {
    type: String,
    required: true
  },
  created: {
    type: Date,
    required: true
  },
  ingredient: {
    type: String,
    required: true
  },
  rating: {
    type: String
  },
  steps: [
    {
      step: { type: String },
      picture: { type: String }
    }
  ],
  comments: [
    {
      comment: { type: String },
      reply: { type: String }
    }
  ],
  pictures: [
    {
      picture: { data: Buffer, type: String, required: true }
    }
  ]
})

let Recipe = (module.exports = mongoose.model('Recipe', RecipeSchema))

我的发布方法和multer的设置如下。

const multer = require('multer')
const storage = multer.diskStorage({
  destination: './route/uploads',
  filename: function(req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
  }
})
const upload = multer({
  storage: storage,
  limits: { fileSize: 1000000 },
  fileFilter: function(req, file, cb) {
    checkFileType(file, cb)
  }
})

function checkFileType(file, cb) {
  const filetypes = /jpeg|jpg|png|gif/
  const extname = filetypes.test(path.extname(file.originalname).toLowerCase())
  const mimetype = filetypes.test(file.mimetype)
  if (mimetype && extname) {
    return cb(null, true)
  } else {
    cb('Error: Images Only!')
  }
}

router.post('/', upload.array('files', 10), (req, res) => {
  let files = req.files

  var recipe = new Recipe()
  for (const key in files) {
    if (files.hasOwnProperty(key)) {
      console.log(files[key].path)
      const fl = fs.readFileSync(files[key].path)
      recipe.pictures.picture.data = fl
      recipe.pictures.picture.type = 'image/png' // or 'image/png'
    }
  }
  recipe.save()
})

我收到此错误

  

TypeError:无法设置未定义的属性“数据”

即使已保存图片,但当我尝试将路径保存到缓冲区时,它也不允许我使用。在猫鼬上,目前尚不清楚如何启动缓冲区的文档。

1 个答案:

答案 0 :(得分:0)

不要将图像(或文件)保存到数据库,只需保存图像名称即可。

修补程序,但不推荐。

pictures是一个数组。

for (const key in files) {
  if (files.hasOwnProperty(key)) {
    console.log(files[key].path)
    const fl = fs.readFileSync(files[key].path)
    recipe.pictures.push({
      picture: {
        data: fl,
        type: 'image/png'
      }
    })
  }
}