如何解决使用 multer 从数据库检索图像
我正在开发 MERN 应用程序,但在显示图像时遇到问题。使用 multer,文件上传成功后,图像路径存储在 MongoDB 中,图像也存储在“uploads”文件夹中,但存在问题我从数据库检索图像路径时得到。
检索到的所有文本数据但显示图像给我错误。
我得到的错误: 无法获取 http://localhost:3000/uploads/image-1614468761737.jpg
这是代码。
const express = require("express")
const path = require("path")
const route = express.Router()
const Post = require("../models/postModel")
const multer = require("multer")
const storage = multer.diskStorage({
destination(req,file,cb){
cb(null,"uploads/")
},filename(req,`${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`)
}
})
const upload = multer({
storage,filefilter: function(req,cb) {
const filetypes = /jpg|jpeg|png/
const extname = filetypes.test(path.extname(file.originalname).toLowerCase())
const mimetype = filetypes.test(file.mimetype)
if(extname && mimetype){
return cb(null,true)
}else{
cb(null,false)
}
},})
route.post("/upload",upload.single("image"),(req,res)=>{
const file = req.file.path.replace(/\\/g,"/" )
res.send(`/${file}`)
})
route.post("/",async(req,res)=>{
const post = req.body
try {
const createpost = new Post(post)
await createpost.save()
res.status(200).json(createpost)
} catch (error) {
res.status(404).json({msg:"create post failed"})
}
})
module.exports = route
在主文件中我也添加
app.use("/uploads",express.static(path.join(__dirname,"/uploads")))
文件结构: file structure and uploads folder is in the root
GitHub: https://github.com/mozi47/Check-error
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。