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

时间:2016-05-17 07:28:23

标签: javascript node.js mongodb express

我已将图像存储到我的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问题的说明进行操作。 &#34;数据&#34;在成功函数中是空的,虽然&#34; image.image&#34;不是空的。有人可以帮帮我吗?

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

1 个答案:

答案 0 :(得分:0)

我认为这对你有用

这是我的模特

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()