nodejs display image stored in gridFS to html

前端 未结 3 1346
醉酒成梦
醉酒成梦 2021-01-16 07:29

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, f         


        
相关标签:
3条回答
  • 2021-01-16 07:53

    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

    0 讨论(0)
  • 2021-01-16 07:59
             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))
                      });   
    
    0 讨论(0)
  • 2021-01-16 08:06

    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);
        }
      });
    };
    
    0 讨论(0)
提交回复
热议问题