使用 mongoose 显示来自 mongodb 的图像

Displaying images from mongodb using mongoose

我目前正在学习 node.js,我正在创建一个小应用程序,我可以在其中上传图像并将它们显示在图库中。

目前我有一个通过 POST

将图像上传到服务器的表单
extends ../layout
block content
.col-sm-6.col-sm-offset-3
  h1 control panel
    form(action="/upload", method="POST",
     enctype="multipart/form-     data")
      input(type="file", name='image')
      input(type="submit", value="Upload Image")

然后使用 mongoose

将文件插入 mongodb
exports.upload = function (req, res) {  
fs.readFile(req.files.image.path, function (err, data) {
    var imageName = req.files.image.name;
    if(!imageName){
        console.log("seems to be an
        error this file has not got a name");
        res.redirect("/");
        res.end();

    }else{
        var newimage = new Image();
        newimage.img.data = fs.readFileSync(req.files.image.path);
        newimage.img.name  = imageName;
        newimage.save(function (err, a) {
              if (err){
                  console.log("There was an error saving the image")
                  res.redirect("/");
                  res.end();
              }
        res.redirect("/gallery");
      });   
    }       
    });
    }

在我的图库控制器中,我查询数据库中的所有图像并将它们传递到前端。

exports.gallery = function (req, res) {
Image.find({}, function(err, image){
if (err)
  res.send(err);
else
    res.render("site/gallery", {images: image });
 });
}

然后在我的图库中,我尝试为每张图片创建一个新的图片标签

extends ../layout
block content
h1 Gallery
  each image in images
    img(src='#{image.img.data}')

我的问题是我不断收到 404 错误,因为浏览器找不到图像。 但我有一种感觉,我可能会以错误的方式去做这件事。我看过 GridFS,但我觉得它不适合这个应用程序,因为图库中的图像数量最多不会超过 20 张。我的做法是正确的还是应该将图像存储在服务器上并以这种方式检索它们?

您通常会将图像上传到服务器的机器文件系统或静态资产云托管服务,如 AWS S3,并仅存储 URL数据库中图像的 s。

您也可以使用类似 Cloudinary 的解决方案。