使用GridF从mongoDB读取和显示图像

时间:2016-01-20 15:33:05

标签: javascript mongodb mongoose gridfs gridfs-stream

我已经能够使用GridF成功将图像上传到mongoDB。 以下是我数据库中的图片:

MongoLab

fs.files:

enter image description here

fs.chunks:

enter image description here

以下是我用来上传图片的代码:

var Grid = require('gridfs-stream');
var mongoose = require("mongoose");
Grid.mongo = mongoose.mongo;
var gfs = new Grid(mongoose.connection.db);

app.post('/picture', function(req, res) {
 var part = req.files.filefield;

            var writeStream = gfs.createWriteStream({
                filename: part.name,
                mode: 'w',
                content_type:part.mimetype
            });


            writeStream.on('close', function() {
                 return res.status(200).send({
                    message: 'Success'
                });
            });

            writeStream.write(part.name);

            writeStream.end();
   });

问题:

我似乎无法弄清楚如何从mongoDB中读取此图像并将其显示在HTML <img>标记的前端。

到目前为止我已尝试过这个,但它只显示文件的名称:

app.get('/picture', function(req, res) {


gfs.files.find({ filename: 'trooper.jpeg' }).toArray(function (err, files) {

    if(files.length===0){
        return res.status(400).send({
            message: 'File not found'
        });
    }

    res.writeHead(200, {'Content-Type': files[0].contentType});

    var readstream = gfs.createReadStream({
          filename: files[0].filename
    });

    readstream.on('data', function(chunk) {
        res.write(chunk);
    });

    readstream.on('end', function() {
        res.end();        
    });

    readstream.on('error', function (err) {
      console.log('An error occurred!', err);
      throw err;
    });
  });
});

我从here

获取了上述代码

任何人都可以帮忙。我已经坚持了这一天!!!!

1 个答案:

答案 0 :(得分:2)

应该是

writeStream.write(part.data);

不是

writeStream.write(part.name);