如何在express js中直接保存base64到mongoose
我想保存一个图像不在我的服务器,但在我的数据库。
这是我的模型
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var categorySchema = new Schema({ img: { data: Buffer, contentType: String }, }); module.exports = mongoose.model('Category', categorySchema);
现在在我的路由器我得到这个base64图像与一个很长的string。
{ '$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'}
在此先感谢我在保存文件。
你会想要从请求主体中拉出base64string,并保存。
req.body.category.img
等于{ '$ngfDataUrl': 'data:image/png;base64,long-String' }
,其中long-String
是图像的base64表示forms?
如果是的话,做这样的事情:
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