我有一個保存在MongoDB上的圖像。該模型如下:從二進制加載圖像(Javascript - Ajax - 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編碼方法將強制。 –
我真的不明白你的意思,你能詳細說明一下嗎? – Drakoumel