【发布时间】:2014-04-19 04:30:40
【问题描述】:
我在 MongoDB 上保存了一张图片。模型如下:
picture: {
metadata: {
name: { type: String, default: null },
comment: { type: String, default: null },
publisherID: { type: String,default: null },
date: { type: Date, default: Date.now },
size: { type: Number,default: 0 },
type: { type: String, default: null }
},
data: { type: Buffer, default: null },
tags: Array
}
现在我需要再次从数据库加载图像。
我进行 AJAX 调用并请求带有 id 的图片。
$.ajax({
type: "POST",
url: window.location.origin + '/picture',
contentType: 'application/json',
dataType: 'json',
async: true,
data: JSON.stringify({ id: id }),
success: function (result) {
console.log(result);
a = result;
var img = result.result[0].picture.data.join("").toString('base64');
img = "data:" + result.result[0].picture.metadata.type + ";base64," + img;
$('#img').attr('src', img);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('error ' + textStatus + " " + errorThrown);
success = false;
}
});
这是服务器上的处理程序
var Picture = require('../models/picture');
Picture.find({ "_id": req.body.id}, function (err, pic) {
if (err || !pic)
res.end(JSON.stringify({ result: "error" }));
if (pic) {
console.log(pic);
res.end(JSON.stringify({ result: pic }));
}
})
我已将二进制数据转换为 base64,但图像不显示。 (我不得不加入二进制数据,因为它们进入了一个数组)。 还有一些其他类似的帖子,但是他们没有我没有做过的任何事情(我认为)。
【问题讨论】:
-
我真的不喜欢这种方法。最好有一个“看起来”是被请求图像的 url 的端点路由。然后数据只是在响应中作为二进制发送。这方面是浏览器缓存而不是总是被请求,因为这种 base64 编码方法会强制执行。
-
我不太明白你的意思,你能详细说明一下吗?
标签: javascript image mongodb binary