Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

html - GridFS : How to display the result of readstream.pipe(res) in an <img/> tag?

I am using MangoDB along with GridFS to store images. I've got this route to retrieve an image from the DB :

app.get("/images/profile/:uId", function (req, res) {
let uId = req.params.uId;
console.log(uId)
gfs.files.findOne(
  {
    "metadata.owner": uId,
    "metadata.type": 'profile'
  }
  , function (err, file) {
    if (err || !file) {
      return res.status(404).send({ error: 'Image not found' });
    }
    var readstream = gfs.createReadStream({ filename: file.filename });
    readstream.on("error", function (err) {
      res.send("Image not found");
    });
    readstream.pipe(res);
  });
});

This returns something like that :

?PNG


IHDR???]?bKGD????   pHYs
?
?B(?xtIME?  -u??~IDATx??i|TU????JDV?fH?0? :-
H_??M??03`???
(??-?q{U[?m?A??AQ?VZ??bP??S?@K@??CB??|??T?[?=????"U??[??{?s?9?  
?+)@e????{?9???,??T.S??xL?x&@?0TSFp7???t????A!_????D?h? 
z????od?G???YzV??e???|?h???@P?,?{???????Z?lvc?N???
n??(?r?.......

It seems like I get the png correctly. How do I display it in an img tag then ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have solved the issue by converting the chunk into base64 string. I then passed the string as below:

  const readstream = gfs.createReadStream(file.filename);
  readstream.on('data', (chunk) => {
    res.render('newHandlebarFile', { image: chunk.toString('base64') });
  })

I render the value in handlebars as below:

  <img src="data:image/png;base64,{{ image }}" alt="{{ image }}"> 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...