I created an image upload API using Multer. The image is also stored in my file and responds back to the path of the image. But I can't preview this image on the browser and also on the frontend.
I save an image in my local folder and get a response as the path of the image. I saved the path in the MongoDB database and want to fetch the image from the database.
//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>
image path/ profile.image value
Image stored in my folder
Maybe I make a mistake somewhere but can't find out. But I think, there is something wrong with the static path. But I didn't find anything wrong.
You can try this:
//server.js
const dirname = path.resolve();
app.use('/uploads', express.static(path.join(dirname, '/uploads')));
//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${profile?.image}`}
alt=""
style={{ height: "10rem", width: "10rem" }}
/>
</div>