本文介绍了nodejs将存储在gridFS中的图像显示为html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hi I'm new to nodejs and gridFSI'm trying to display images stored in gridFS to my html page

当前,我正在使用此代码.

Currently, I am using this code.

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下载图像.如果我的服务器存储空间不足,那应该是有问题的

But my code need to download image from gridFS. If my server storage is not enough, it should be problematic

是否有任何方法可以将gridFS图像直接显示为html?

Is there any method to display gridFS images to html directly?

推荐答案

在images目录中添加资源路由,然后像这样直接将gridfs readstream通过管道传递给响应

Add a route for resources in your images directory and pipe the gridfs readstream to the response directly like so

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

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

In your html, all you need to do is specify the src url in your images correctly

这篇关于nodejs将存储在gridFS中的图像显示为html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 13:52