正确的语法是使用multer在我的MERN前端中显示MongoDB图像是什么?

huangapple go评论51阅读模式
英文:

What is the correct syntax for displaying MongoDB images in my MERN frontend using multer?

问题

我正在尝试发出GET请求以接收存在于我的MongoDB中的帖子。我正在使用multer中间件,并且在前端显示图像方面遇到了困难。

我的后端代码如下:
(posts.js)

import express from "express";
import multer from "multer";
import Posts from "../models/posts.js";

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads/");
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + "-" + file.originalname);
  },
});

const upload = multer({ storage: storage });

const router = express.Router();

router.route("/create").post(upload.single('file'), async (req,res)=>{
  try {
    const post = new Posts({
      title: req.body.title,
      description: req.body.description,
      amt: req.body.amt,
      artist_name: req.body.artist_name,
      art_image: req.file.filename,
    });

    const savedPodcast = await post.save();
    res.status(201).json(savedPodcast);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: "Internal server error" });
  }
});

router.route("/feed").get( async (req, res) => {
  try {
    const getPosts = await Posts.find();
    console.log(getPosts)
    res.json(getPosts);
  } catch (error) {
    res.status(500).json({ message: "Error fetching posts", error });
  }
});

export default router

此代码与app.use('/feed', feedRoute)相关联并被调用。我的GET请求正确地从数据库中检索数据,如下所示:

[
  {
    _id: new ObjectId("6479438fdf4ff1fc5cf2eab8"),      
    artist_name: 'sad',
    title: 'gfds',
    description: 'adf',
    amt: '234',
    reportCount: 0,
    upvote: 0,
    createdAt: 2023-06-02T01:19:02.297Z,
    art_image: '1685668751687-event_juntion.png',       
    apply_watermark: true,
    __v: 0
  }
]

但是,我不知道如何使用art_image文件路径在前端显示它。我应该在img标签的src中写什么?

英文:

I am trying to make a get request to receive the posts that exist in my MongoDB. I am using multer middleware and am struggling to display the images in the frontend.

My backend code looks like:
(posts.js)

import express from "express";
import multer from "multer";
import Posts from "../models/posts.js";
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "uploads/");
},
filename: function (req, file, cb) {
cb(null, Date.now() + "-" + file.originalname);
},
});
const upload = multer({ storage: storage });
const router = express.Router();
router.route("/create").post(upload.single('file'), async (req,res)=>{
try {
const post = new Posts({
title: req.body.title,
description: req.body.description,
amt: req.body.amt,
artist_name: req.body.artist_name,
// Use fileType instead of req.body.type
art_image: req.file.filename,
});
const savedPodcast = await post.save();
res.status(201).json(savedPodcast);
} catch (err) {
console.error(err);
res.status(500).json({ message: "Internal server error" });
}
});
router.route("/feed").get( async (req, res) => {
try {
const getPosts = await Posts.find();
console.log(getPosts)
res.json(getPosts);
} catch (error) {
res.status(500).json({ message: "Error fetching posts", error });
}
});
export default router

This code is tied to app.use('/feed', feedRoute) and gets called. My get request retrieves the data in my database correctly as:

[
{
_id: new ObjectId("6479438fdf4ff1fc5cf2eab8"),      
artist_name: 'sad',
title: 'gfds',
description: 'adf',
amt: '234',
reportCount: 0,
upvote: 0,
createdAt: 2023-06-02T01:19:02.297Z,
art_image: '1685668751687-event_juntion.png',       
apply_watermark: true,
__v: 0
}
]

However, I am not able to understand how to use the art_image file path to display it in front end. What should I write in the src of the img tag?

答案1

得分: 0

你需要从服务器提供上传的文件。

你可以将整个 uploads 文件夹作为静态文件夹提供:

app.use(express.static(path.join(__dirname, 'uploads')));

然后将 art_image 的值添加到 src

<img src="1685668751687-event_juntion.png" />

(你也可以添加虚拟路径):

app.use('/images', express.static(path.join(__dirname, 'uploads')));
<img src="images/1685668751687-event_juntion.png" />

或者,你可以通过在每个请求上使用 sendFile 来为每个文件提供服务,通过添加一个新的路由,该路由将通过 req.params 获取文件名,这种方法不会使整个 uploads 文件夹都可以访问:

app.get("/images/:image", (req, res) => {
    res.sendFile(path.join(__dirname, 'uploads', req.params.image));
});
<img src="images/1685668751687-event_juntion.png" />

查看更多适合你的选项:

https://stackoverflow.com/questions/31425284/express-static-vs-res-sendfile

英文:

You need to serve uploaded files from the server.

You could serve entire uploads folder as a static folder:

app.use(express.static(path.join(__dirname, &#39;uploads&#39;)));

and then add art_image value to the src:

&lt;img src=&quot;1685668751687-event_juntion.png&quot; /&gt;

(you can also add a virtual path):

app.use(&#39;/images&#39;, express.static(path.join(__dirname, &#39;uploads&#39;)));

<!-->
<img src="images/1685668751687-event_juntion.png" />

<br/>

Or, you could serve each file with sendFile upon each request, by adding a new route, which would take file name via req.params, and that approach wouldn't make the whole uploads folder accessible:

app.get(&quot;/images/:image&quot;, (req, res) =&gt; {
res.sendFile(path.join(__dirname, &#39;uploads&#39;, req.params.image));
});

<!-->

&lt;img src=&quot;images/1685668751687-event_juntion.png&quot; /&gt;

See more which option would suit you:

https://stackoverflow.com/questions/31425284/express-static-vs-res-sendfile

huangapple
  • 本文由 发表于 2023年6月2日 10:05:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76386715.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定