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.
This is part of what is saved in mongodb:
{
"_id": {
"$oid": "58f2e56fd8ca891e02fc85db"
},
"path": "uploads/1492313455338_codi.jpg",
"filename": "1492313455338_codi.jpg",
"__v": 0,
"article": {
"$oid": "58f2e56fd8ca891e02fc85dc"
}
}
Schema:
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
});
});
Part of ejs to upload file
<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 to retrieve file:
<div class="col-md-4">
<form method="GET" action="/blog/article/<%= image.id %>">
<img src="<%= image.path %>" style="width:304px;height:228px;">
</form>
</div>
multer configuration:
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);
}
}
});
答案 0 :(得分:0)
我从未使用过multer所以我不确定如何引导你完成它。
但是,我确实使用强大的上传图像,我已经为我的图像创建了一个公共文件夹,每次上传图像时都会保存我的数据库中的保存路径,这样你就可以直接访问dir并在你的ejs文件中实现它。
希望我的回答是相关的。
祝你好运答案 1 :(得分:0)
我不得不删除&#39; public&#39;从路上。这jsFiddle帮助我解决了问题