nodejs display image stored in gridFS to html

余生长醉 提交于 2019-12-01 10:28:57

问题


Hi I'm new to nodejs and gridFS I'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'
                }); 
            }); 
        }
    });

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

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


回答1:


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

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




回答2:


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



回答3:


Try the function like below,

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


来源:https://stackoverflow.com/questions/31197463/nodejs-display-image-stored-in-gridfs-to-html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!