javascript - 我正在尝试使用 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))
我的 post 方法和 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:无法设置未定义的属性“数据”
即使保存了图片,当我尝试将路径保存在缓冲区上时,它也不允许我这样做。在猫鼬上,文档现在还不清楚如何启动缓冲区。
解决方案
不要将图像(或文件)保存到数据库,只保存图像名称。
修补程序,但不推荐。
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'
}
})
}
}
推荐阅读
- flutter - Flutter 中基于 REST api 的应用程序的最佳设计模式?
- django-templates - 我是 Django 的新手。静态文件无法工作。bt 我为静态设置了完美的目录。谁能帮我解决这个问题?
- javascript - 每次以 HTML 重新加载页面时如何打开新视频
- flutter - 如何结合使用 PageView 和 max drawerEdgeDragWidth
- java - java中有没有一种方法可以格式化像“1.551121004×10^25”这样的很长的数字?
- javascript - 三人以上webRTC数据通道
- mysql - 使用 MySql 5.5.62 创建带有 ORDER BY 的序列列
- rust - Rust中取模求幂密码函数的优化实现
- php - 浏览器在运行此 php 代码时显示一些语法错误
- javascript - 阅读 Next.js 错误