Display image in HTML from GridFS

廉价感情. 提交于 2019-12-04 02:31:12

问题


I'm uploading an image in GridFS but have no idea how to display this in an <img > tag.

I tried the following code:

conn.once('open', function () {
    var gfs = Grid(conn.db, mongoose.mongo);
    gfs.files.find({ filename: 'img1.png' }).toArray(function (err, files) {
        if (err) { console.log(err); }
        console.log(files);
    });
});

I get the result:

[ { _id: 5316f8b3840ccc8c2600003c,
    filename: 'img1.png',
    contentType: 'binary/octet-stream',
    length: 153017,
    chunkSize: 262144,
    uploadDate: Wed Mar 05 2014 15:43:07 GMT+0530 (India Standard Time),
    aliases: null,
    metadata: null,
    md5: '915c5e41a6d0a410128b3c047470e9e3' } ]

Now this is just the file info not the actual file data.

How to display image in HTML?


回答1:


You have to define the Content-Type for the response, and using db connection you can fetch the data. Check the following example to get an idea:

app.get('/filelist', function(req, res) {
    var collection = db.collection('DbCollectionName');
    var da = collection.find().toArray(function(err, items) {
        console.log(items[0]);
        res.writeHead(200, {'Content-Type': 'image/png'});
        res.end(items[1].dbfileName.buffer, 'binary');
    });
});

Edit :

So when you want to set the image as the source, you can convert the binary data of the image(fetched from db) to base64 format.

var img = document.createElement('img');
img.src = 'data:image/jpeg;base64,' + btoa('your-binary-data'); //JS have btoa() function for it.
document.body.appendChild(img);

or you can use hex to base64 also if your image doesn't support above

function hexToBase64(str) {
return btoa(String.fromCharCode.apply(null, str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")));
}

and call it as

img.src = 'data:image/jpeg;base64,' + hexToBase64('your-binary-data');


来源:https://stackoverflow.com/questions/22196125/display-image-in-html-from-gridfs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!