繁体   English   中英

使用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存储在数据库中。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM