【问题标题】:Reading and Displaying images from mongoDB using GridFs使用 GridFs 从 mongoDB 读取和显示图像
【发布时间】:2016-04-26 13:00:09
【问题描述】:

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

fs.files:

fs.chunks:

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

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

谁能帮忙。我已经坚持了好几天了!!!!

【问题讨论】:

    标签: javascript mongodb mongoose gridfs gridfs-stream


    【解决方案1】:

    应该是这样的

    writeStream.write(part.data);
    

    不是

    writeStream.write(part.name);
    

    【讨论】:

    • 再次感谢您的回答。如果我使用 part.data 它会在运行时出现错误,说无法读取未定义的属性“长度”。有什么线索吗?
    • 您忘记添加busboy-body-parser 中间件?它在你提到的教程中:codetutorial.io/file-upload-gridfs-mean-stack-meanjs/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-27
    • 2014-02-25
    • 2012-11-15
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多