检索MongoDB binData并显示为<img>src

Retrieve MongoDB binData and display as <img> src

本文关键字:lt gt src img MongoDB binData 显示 检索      更新时间:2023-09-26

我已经将一个图像存储到我的mongoDB集合中,它看起来像:

{
  "photo" : {
    "image" : BinData(0,"/9j/4AAQS......"),
    "imageType": "image/jpeg"
  }
}

我的路由器看起来像:

app.get('/userImage', function(req, res) {
  var username = req.user.username;
  User.getProfilePicture(username, function(err, image) {
    if (err) {
      res.end('Error fetching photo');
    }
    res.setHeader('Content-Type', image.imageType);
    res.end(image.image.buffer, 'binary');
  });
});

模型看起来像:

exports.getProfilePicture = function(username, callback) {
  var collection = db.get().collection('users');
  collection.find({ 'username': username }).toArray(function(err, users) {
    callback(err, users[0].photo);
  });
};

ajax请求:

$.ajax({
  type: 'GET',
  url: '/userImage',
  success: function(data) {
    console.log(data);
    $image.src = data;
  }
});

在console.log上,我会:

console.log(image);

我得到:

{ image: 
   Binary {
     _bsontype: 'Binary',
     sub_type: 0,
     position: 42461,
     buffer: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 02 00 00 01 00 01 00 00 ff db 00 43 00 05 03 04 04 04 03 05 04 04 04 05 05 05 06 07 0c 08 07 07 07 07 0f 0a 0b 09 ... > },
  imageType: 'image/jpeg' }

这里发生了一些错误,尽管我遵循了其他资源和stackoverflow问题的指示。成功函数中的"data"为空,尽管"image.image"不为空。有人能帮我吗?

从这个console.log,有人能告诉我如何在html中显示图像吗?

我认为这对u 很有用

这是我的型号

var ImageSchema = new mongoose.Schema({
"photo" : {
"image" : Buffer,
    "imageType":{type:String}}});
var Image = mongoose.model('Error', ImageSchema);
module.exports = Image;

我的数据像这个一样存储

{
"photo" : {
"image" : BinData(0,"/9j/4AAQS......"),
"imageType": "image/jpeg"}}

获取函数

var Image = require(. / Image)
app.get('/image/:imageId', function(req, res) {
Image.findbyId(imageId, function(err, imagedata) {
    if (err)
        return err
    res.end(imagedata.photo.image);
})});

最后ajax调用

$.ajax({
type: 'GET',
url: '/image/123:',
success: function(data) {
    console.log(data);
    $image.src = data
}});

和res.end()将直接发送图像数据不使用res.send()