【发布时间】:2020-11-06 14:54:33
【问题描述】:
我一直在关注 YouTube 上的这个很棒的教程,试图建立一个网站。但是,一旦我部署它,图像就不会显示,因为目前它们都保存在一个名为 uploads 的本地文件夹中。这就是它现在的样子:
服务器端:
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/')
},
filename: (req, file, cb) => {
cb(null, `${Date.now()}_${file.originalname}`)
},
fileFilter: (req, file, cb) => {
const ext = path.extname(file.originalname)
if (ext !== '.jpg' || ext !== '.png') {
return cb(res.status(400).end('only jpg, png are allowed'), false);
}
cb(null, true)
}
})
var upload = multer({ storage: storage }).single("file")
router.post("/uploadImage", auth, (req, res) => {
upload(req, res, err => {
if(err) return res.json({success: false, err})
return res.json({ success: true, image: res.req.file.path, fileName: res.req.file.filename})
})
});
CLIENT SIDE:图片字段存储一个字符串(即“uploads\xxxxxxxx.jpg”)
function ProductImage(props) {
const [Image, setImage] = useState();
useEffect(() => {
setImage(`http://localhost:5000/${props.detail.image}`)
}, [props.detail])
return(
<div>
<img style={{maxWidth: '30vw'}}
src={Image} alt="productImg"/>
</div>
)
}
所以我想我现在的问题是我该如何实际将图像上传到 MongoDB,以及如何检索它们?
【问题讨论】:
标签: node.js reactjs mongodb express multer