我使用Multer创建了一个图像上传API.图像也存储在我的文件中,并响应图像的路径.但我不能在浏览器和前端预览这张图片.
我在本地文件夹中保存了一个图像,并得到了作为该图像路径的响应.我将路径保存在MongoDB数据库中,并希望从数据库中获取图像.
//upload router
import express from "express";
import multer from "multer";
import path from "path";
import { Request, Response } from "express";
const router = express.Router();
const 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)}`
);
},
});
const upload = multer({ storage: storage });
router.post("/", upload.single("image"), (req: any, res: Response) => {
const imgUrl = req.file.path.replace(/\\/g, "/");
console.log(imgUrl);
res.send(`/${imgUrl}`);
});
export default router;
//server.js
app.use("/api/v1/uploads", imageUpload);
app.use("/uploads", express.static(path.join(__dirname, "/uploads")));
//image input
const uploadImgHandler = async (e: any) => {
const file = e.target.files[0];
const formData = new FormData();
formData.append("image", file);
setUploadingImg(true);
try {
const config = {
headers: {
"Content-Type": "multipart/form-data",
},
};
const { data } = await axios.post(
"http://localhost:5000/api/v1/uploads",
formData,
config
);
console.log("data", data);
setEmployeeImg(data);
setUploadingImg(false);
} catch (error) {
console.error(error);
setUploadingImg(false);
}
};
// input jsx
<input
accept="image/*"
name="image"
id="contained-button-file"
type="file"
style={{ padding: 10 }}
onChange={uploadImgHandler}
/>
//fetch image
<div>
<p>Address: {profile?.address}</p>
<p>Salary: {profile?.salary}</p>
<p>Joinning Date: {profile?.joingDate}</p>
<p>image</p>
<img
src={`http://localhost:5000/api/v1/uploads${profile?.image}`}
alt=""
style={{ height: "10rem", width: "10rem" }}
/>
</div>
图像路径/配置文件.图像值
存储在我的文件夹中的图像
也许我在什么地方弄错了,但找不到.但我认为,静态路径有问题.但我没有发现任何问题.