【问题标题】:Displaying images from mongodb using mongoose使用 mongoose 显示来自 mongodb 的图像
【发布时间】:2015-05-09 20:13:40
【问题描述】:

我现在正在学习 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 个。我是在采用正确的方法来执行此操作,还是应该将图像存储在服务器上并以这种方式检索它们?

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-21
      • 1970-01-01
      • 2013-02-26
      • 1970-01-01
      • 2018-03-15
      相关资源
      最近更新 更多