作者:kanliyan_857 | 来源:互联网 | 2023-01-30 17:30
我有一个base64的图像,例如
data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAAQABAAD/7QCcUGhvdG9zaG9w....
如何保存在数据库中?模式中字段的类型应该是什么?缓冲?
1> Neil Lunn..:
简短的回答是存储为"二进制",您可以使用mongoose模式Buffer
来执行此操作.
较长的形式是演示从原始二进制开始并再次返回的转换往返.在大多数现实世界的情况下,Base64编码/解码不是必要的步骤,只是用于演示:
从文件中读取图像(或任何二进制数据)
Base64对该数据进行编码(只是为了表明它可以完成) - 可选
转回Base64中的二进制数据(只是为了表明它可以完成) - 可选
将二进制数据存储在数据库中
从数据库中读取二进制数据
将二进制数据输出到新文件
因此Schema Part很简单,只需使用Buffer
:
var albumSchema = new Schema({
name: String,
image: Buffer
})
然后所有要做的就是按照流程将二进制数据放入属性并再次读回来.
请注意,如果您直接来自具有MIME类型的字符串,例如:
data:image/png;base64,long-String
只需使用Javascript .split()
并获取base64字符串本身的第二个数组索引:
var string = "data:image/png;base64,long-String"
var bindata = new Buffer(string.split(",")[1],"base64");
这是一个包含完整演示的列表:
const async = require('async'),
mOngoose= require('mongoose'),
Schema = mongoose.Schema,
fs = require('fs');
mongoose.Promise = global.Promise;
mongoose.set('debug',true);
mongoose.connect('mongodb://localhost/test');
var albumSchema = new Schema({
name: String,
image: Buffer
})
const Album = mongoose.model('Albumn', albumSchema);
async.series(
[
(callback) =>
async.each(mongoose.models,(model,callback) =>
model.remove({},callback),callback),
(callback) =>
async.waterfall(
[
(callback) => fs.readFile('./burger.png', callback),
(data,callback) => {
// Convert to Base64 and print out a bit to show it's a string
let base64 = data.toString('base64');
console.log(base64.substr(0,200));
// Feed out string to a buffer and then put it in the database
let burger = new Buffer(base64, 'base64');
Album.create({
"title": "burger",
"image": burger
},callback)
},
// Get from the database
(album,callback) => Album.findOne().exec(callback),
// Show the data record and write out to a new file.
(album, callback) => {
console.log(album);
fs.writeFile('./output.png', album.image, callback)
}
],
callback
)
],
(err) => {
if (err) throw err;
mongoose.disconnect();
}
)
注意该示例最初是使用asyncJS和较旧的mongoose API提供的,它们具有不同的连接选项,如更现代和当前的API示例所示.请参考这些来测试当前的NodeJS LTS版本:
或者使用更现代的语法和API用于比较:
const fs = require('mz/fs');
const { Schema } = mOngoose= require('mongoose');
const uri = 'mongodb://localhost:27017/test';
const opts = { useNewUrlParser: true };
mongoose.Promise = global.Promise;
mongoose.set('debug', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
const albumSchema = new Schema({
name: String,
image: Buffer
});
const Album = mongoose.model('Album', albumSchema);
(async function() {
try {
const cOnn= await mongoose.connect(uri, opts);
await Promise.all(
Object.entries(conn.models).map(([k, m]) => m.deleteMany())
)
let data = await fs.readFile('./burger.png');
// Convert to Base64 and print out a bit to show it's a string
let base64 = data.toString('base64');
console.log(base64.substr(0,200));
// Feed out string to a buffer and then put it in the database
let burger = new Buffer(base64, 'base64');
await Album.create({ "title": "burger", "image": burger });
// Get from the database
// - for demo, we could have just used the return from the create() instead
let album = Album.findOne();
// Show the data record and write out to a new file.
console.log(album);
await fs.writeFile('./output.png', album.image)
} catch(e) {
console.error(e);
} finally {
mongoose.disconnect()
}
})()
即使是"普通承诺",要么是首选,要么你仍然在没有async/await
支持的情况下使用NodeJS .但是你真的不应该这样,考虑到v6.x在2019年4月到达终点:
// comments stripped - refer above
const fs = require('mz/fs');
const { Schema } = mOngoose= require('mongoose');
const uri = 'mongodb://localhost:27017/test';
const opts = { useNewUrlParser: true };
mongoose.Promise = global.Promise;
mongoose.set('debug', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
const albumSchema = new Schema({
name: String,
image: Buffer
});
mongoose.connect(uri, opts)
.then(cOnn=>
Promise.all(
Object.entries(conn.models).map(([k, m]) => m.deleteMany())
)
)
.then(() => fs.readFile('./burger.png'))
.then(data => {
let base64 = data.toString('base64');
console.log(base64.substr(0,200));
let burger = new Buffer(base64, 'base64');
return Album.create({ "title": "burger", "image": burger });
})
.then(() => Album.findOne() )
.then(album => {
console.log(album);
return fs.writeFile('./output.png', album.image)
})
.catch(console.error)
.then(() => mongoose.disconnect());
这里有一个burger.png玩:
同样值得称道如何减少Stack Overflow上的图像大小,这样可以使这里的样本图像不像原来那样显得"巨大",但仍然可以全尺寸下载.