检索存储在 mongodb 中的图像

Retrieving images stored in mongodb

I have tried to retrieve images I uploaded and saved to mongodb but I am not able to retrieve back the image directly from db. There seems to be a lot of information about uploading files but not a lot of information about retrieving the uploaded images from the db.

I would really appreciate your help. Thanks in advance.

这是 mongodb 中保存的部分内容:

{
    "_id": {
        "$oid": "58f2e56fd8ca891e02fc85db"
    },
    "path": "uploads/1492313455338_codi.jpg",
    "filename": "1492313455338_codi.jpg",
    "__v": 0,
    "article": {
        "$oid": "58f2e56fd8ca891e02fc85dc"
    }
}

架构:

var mongoose = require('mongoose');

var ImageSchema = new mongoose.Schema({
  img: { data: Buffer, contentType: String }
});

module.exports = mongoose.model('Image', ImageSchema);

router.js

router.post('/blog/article/addPost', upload.single('image'), function(req, res, err) {
  var image = new Image ({
    path: req.file.path,
    filename: req.file.filename
  });
    image.save(function(err, image) {
          //other code
        });
});

上传文件的部分ejs

<form action="/blog/article/addPost" method="post" enctype="multipart/form-data">
        <div class="form-group">
          <label="name">Add a picture for your article</label>
          <input id="upload-input" type="file" class="form-control" name="image"/>
        </div>
</form>

ejs 检索文件:

<div class="col-md-4">
        <form method="GET" action="/blog/article/<%= image.id %>">
          <img src="<%= image.path %>" style="width:304px;height:228px;">
        </form>
</div>

多种配置:

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './public/uploads/')
  },
  filename: function (req, file, cb) {
    if (!file.originalname.match(/\.(png|jpeg|jpg|wav|tif|gif)$/)) {
      var err = new Error();
      err.code = 'filetype';
      return cb(err);
    } else {
      cb(null, Date.now() + "_" + file.originalname);
    }

  }
});

我从未使用过 multer,所以我不确定如何指导您使用它。

但是,我确实使用 formidable 来上传图片,我所做的是为我的图片创建了一个 public 文件夹,每次我上传图片时,我都会将保存路径保存在我的数据库中,这您可以直接访问目录并在您的 ejs 文件中实现它的方式。

希望我的回答是相关的。

祝你好运

我不得不从路径中删除 'public'。这 帮助我解决了问题