node.js - express js中如何将base64直接保存到mongoose

标签 node.js mongodb express 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 图像。

{ '$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/

相关文章:

node.js - 在 Windows 7 上使用 Ax 辅助工具运行 Node js 脚本时遇到问题。

node.js - mongoDB 中数据库更新后查询未给出更新结果

mongodb - 将 localhost 添加到 mongo atlas 白名单

node.js - 缺少必需参数 : redirect_uri with passport-google-oauth

javascript - 查询对象。 "q"查询不起作用

arrays - 在 Node.js 中异步添加到数组

javascript - NodeJS mysql2 Bluebird ?

java - 如何使用 mongoDB 条件查询在 java 中获得更干净的代码

node.js - 如何检查nodejs中的标题?

node.js - 在expressjs中获取发出请求的客户端的ip地址