我不想将图像保存在我的服务器中,而是保存在我的数据库中。
这是我的模型
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var categorySchema = new Schema({
img: { data: Buffer, contentType: String },
});
module.exports = mongoose.model('Category', categorySchema);
现在在我的路由器中,我得到了这个带有长字符串的 base64 图像。
{ '$ngfDataUrl': 'data:image/png;base64,long-String'}
我想知道如何将这些信息保存在我的 mongoose db 数据库中。
router.post('/add', function (req, res) {
var category = new Category();
category.img.data = req.body.category.img;
category.img.contentType = 'image/png';
category.save(function (err) {
if (err) throw new Error(err);
res.sendStatus(200)
});
但显然这不起作用,我收到此错误。
Error: ValidationError: CastError: Cast to Buffer failed for value "{ '$ngfDataUrl': 'data:image/png;base64, long-String'}
提前致谢,我正在保存文件。
最佳答案
您实际上需要从请求正文中提取 base64 字符串,并保存它。
req.body.category.img
是否等于 { '$ngfDataUrl': 'data:image/png;base64,long-String' }
,其中 long-String
是图片的base64表示吗?
如果是这样,做这样的事情:
const category = new Category();
const img = req.body.category.img;
const data = img['$ngfDataUrl'];
const split = data.split(','); // or whatever is appropriate here. this will work for the example given
const base64string = split[1];
const buffer = Buffer.from(base64string, 'base64');
category.img.data = buffer;
// carry on as you have it
关于node.js - express js中如何将base64直接保存到mongoose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39711217/