我正在使用MangoDB和GridFS来存储图像。我有这条路线从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);
});
});
这会返回类似的内容:
�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�l\vc�NӲ�?
n��(�r�.......
好像我正确地得到了png。我如何在img标签中显示呢?
答案 0 :(得分:2)
我已通过将块转换为base64字符串解决了该问题。然后,我将字符串传递如下:
const readstream = gfs.createReadStream(file.filename);
readstream.on('data', (chunk) => {
res.render('newHandlebarFile', { image: chunk.toString('base64') });
})
我在车把中渲染值,如下所示:
<img src="data:image/png;base64,{{ image }}" alt="{{ image }}">
答案 1 :(得分:0)
exports.itemimage = 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);
}
});
};
答案 2 :(得分:0)
我得到了答案 您要做的就是在设置路由时,在img src中输入URL
app.get('/image/:filename', (req, res) => {
gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
// Check if file
if (!file || file.length === 0) {
return res.status(404).json({
err: 'No file exists'
});
}
// Check if image
if (file.contentType === 'image/jpeg' || file.contentType === 'image/png') {
// Read output to browser
const readstream = gfs.createReadStream(file.filename);
readstream.pipe(res)
} else {
res.status(404).json({
err: 'Not an image'
});
}
});
});
而且有效