首页 > 解决方案 > 从 mongo 检索图像文件到我的主页

问题描述

嗨,我试图在 MongoDB 中上传我的图像,然后在我的主页上显示它们我使用 multer 将其上传到我的文件系统,并将它们与其他一些信息一起添加到我的数据库中,我可以存储它们,但虽然我没有得到图像未显示在我的主页上的任何错误,这是我的代码:这是我的服务器代码 app.js :

require("dotenv").config();
const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const multer = require("multer");
const fs = require("fs");
const mongoose = require("mongoose");
const app = express();

var storage = multer.diskStorage({
destination: function(req, file, cb){
cb(null, 'uploads')
},
filename: function(req, file, cb){
cb(null, file.fieldname+ '-' + Date.now() + path.extname(file.originalname));
}
})
var upload = multer({
storage:storage
})
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname + "/public"));

mongoose.connect("mongodb://localhost:27017/behnampostDB",{useNewUrlParser: true,
useUnifiedTopology: true});
const postSchema = {
date: String,
title: String,
post: String,
image: {
    data: Buffer,
    contentType: String
}
};
const Post = mongoose.model("Post", postSchema);
app.post("/compose", upload.single('imagePost'), function(req, res){

const post= new Post ({
date: req.body.postDate,
title: req.body.postTitle,
post : req.body.postBody,
image: {
        data: fs.readFileSync(path.join(__dirname + '/uploads/' + 
         req.file.filename).toString('base64')),
        contentType: 'image/jpg'
    }
})
Post.insertMany(post, function(err){
    if (err) {
      console.log(err);
    } else {
      console.log("Successfully savevd posts to DB.");
      res.redirect("/");

    }
  });
});

app.get("/compose", function(req, res){
res.render("compose");
});


const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}...`);
});

这是我的 home.js 代码:

 <% posts.forEach(function(post){%>
 <header>
 <span class="date"><%=  post.date  %></span>
 <h2><%=  post.title  %></h2>
 </header>
 <a href="#" class="image fit"><img 
 src="data:image/<%=post.image.contentType%>;base64,
 <%=post.image.data%>"/></a>
 <p><%=  post.post.substring(0, 50) + "..."  %></p>
 <ul class="actions special">
 <li><a href="#" class="button">Read more</a></li>
 </ul>
  <% }) %>

这是我要使用的表格:

<div class="row mb-3">
<label class="col-sm-2 col-form-label ">Title</label><br>
<div class="form-floating">
<input type="text" name="postTitle" placeholder="Title" class="form-control" id="inputEmail3" 
 autocomplete="off"><br>
<input type="date" name="postDate" placeholder="Date" class="form-control" id="inputEmail3" 
 autocomplete="off"><br><br>
<input type="file" name="imagePost" placeholder="Image" class="form-control" id="inputEmail3" 
 autocomplete="off">
</div>
</div>
<div class="row mb-3">
<label  class="col-sm-2 col-form-label">Post</label><br>
<div class="form-floating">
<textarea class="form-control" name="postBody" placeholder="Write post here" 
id="floatingTextarea2" style="height: 100px"></textarea>
</div>
</div>
<br><br>
<button type="submit" name="button" class="btn btn-primary">Publish</button>
</form>

请帮我

标签: javascriptnode.jsmongodbexpressmulter

解决方案


image.data在 MongoDB 模式中定义为 Buffer,但代码在存储到数据库之前将 Buffer 转换为 base64。

试试这个:

const path = path.join(__dirname, '/uploads/', req.file.filename);
const fileBuffer = fs.readFileSync(path);

const post = new Post({
  ...,
  image: {
    data: fileBuffer,
    ...
  },
});

推荐阅读