nodejs将存储在gridFS中的图像显示为html

时间:2015-07-03 02:18:01

标签: mongodb gridfs

您好我是nodejs和gridFS的新手 我正在尝试将存储在gridFS中的图像显示到我的html页面

目前,我正在使用此代码。

gfs.exist(options, function(err, found){
        if(err) return handleError(err);
        if(found)
        {
            console.log("Found Image");
            var fs_write_stream = fs.createWriteStream('public/images/'+req.user._id + '_photo' + '.jpg');
            var readstream = gfs.createReadStream({
                filename: req.user._id + '_photo'
            });
            readstream.pipe(fs_write_stream);
            readstream.on('close', function(){
                console.log('file has been written fully');
                res.render('profile', {
                    user : req.user,
                    message: req.flash('info'),
                    user_photo_url: 'images/'+req.user._id+'_photo.jpg'
                }); 
            }); 
        }
    });

但是我的代码需要从gridFS下载图像。如果我的服务器存储空间不足,则应该存在问题

有没有方法可以直接将gridFS图像显示为html?

3 个答案:

答案 0 :(得分:2)

在images目录中添加资源路由,并将gridfs readstream直接传递给响应

app.get('/images/:name', function(req, res) {
    var readstream = gfs.createReadStream({
        filename: req.param('name');
    });
    res.pipe(readstream);
})

在您的html中,您需要做的就是正确指定图片中的src网址

答案 1 :(得分:1)

         var pi_id   =  fields.pic_id;

         gfs.findOne({ _id: pi_id }, function (err, file) {
                    console.log(file);
                    if (err) return res.status(400).send(err);
                    if (!file) return res.status(404).send('');

                    res.set('Content-Type', file.contentType);
                    res.set('Content-Disposition', 'attachment; filename="' + file.filename + '"');

                    var readstream = gfs.createReadStream({
                      _id: file._id
                    });

                    readstream.on("error", function(err) {
                      console.log("Got error while processing stream " + err.message);
                      res.end();
                    });

                    readstream.pipe(res);

                    console.log(readstream.pipe(res))
                  });   

答案 2 :(得分:0)

尝试如下功能,

function(req,res){
  gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
    res.contentType(file.contentType);
    // Check if image
    if (file) {
      // Read output to browser
      const readstream = gfs.createReadStream(file.filename);
      readstream.pipe(res);
    } else {
        console.log(err);
    }
  });
};