使用GridF从mongoDB读取和显示图像 [英] Reading and Displaying images from mongoDB using GridFs

查看:467
本文介绍了使用GridF从mongoDB读取和显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been able to successfully upload images to mongoDB using GridFs. Below are images from my database:

fs.files:

fs.chunks:

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

Below is the code I used to upload images:

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>标记的前端.

I can't seem to figure out how to read this image from mongoDB and display it on the front end in a HTML <img> tag.

到目前为止,我已经尝试过,但是它仅显示文件名:

I have tried this so far but it only displays the name of the file:

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;
    });
  });
});

我从这里

任何人都可以帮忙.我已经在DAYS卡住了!!!!

Can anyone please help. Ive been stuck on this for DAYS!!!!

推荐答案

应该确实是

writeStream.write(part.data);

不是

writeStream.write(part.name);

这篇关于使用GridF从mongoDB读取和显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆