When sending data from the frontend, ensure you follow this structure:
let formData = new FormData()
formData.append("image", file)
axios.post("/api/saveimage",formData)
Firstly, create a FormData
and append the file to it. In this example, the file is named image
. Next, you will need to use multer
on your nodejs backend.
npm i multer
To start, create a middleware:
const multer = require("multer");
const whitelist = ["image/png", "image/jpeg", "image/jpg", "image/webp"];
const storeImages = multer.diskStorage({
destination: async function (req, file, cb) {
if (!whitelist.some((type) => type === file.mimetype)) {
return cb(new Error("File is not allowed"), "/");
}
cb(null, "your/destination/path");
},
filename(req, file, cb) {
let [name] = file.originalname.split(".");
cb(null, name + ".png");
},
});
exports.uploadImageStorage = multer({
storage: storeImages,
});
Ensure that your destination path exists and include an extension for your file, such as .png
.
Now, create your route:
const { uploadImageStorage } = require("../yourstorage")
app.post("/api/saveimage", uploadImageStorage.single("image"), (req, res) => {
let file = req.file
let path = file.path
})
Be sure that the parameter in
uploadImageStorage.single("image")
matches the one used in
formData.append("image", file)
.
You can save the file path in a database and optionally manipulate the image using sharp
.
If you have a folder named static
with an image like photo.png
inside, you would typically access it via localhost:3000/photo.png
, not localhost:3000/static/photo.png
.
If you encounter this setup, remember to remove static
from the path to correctly display the image on the frontend.