Well at the frontend you need to send it like this:
let formData = new FormData()
formData.append("image", file)
axios.post("/api/saveimage",formData)
At the first step you create a FormData
, then you append the file. In this case i named the file image
. Now lets go to the next step. You will need multer
on your nodejs side.
npm i multer
The first think you need to do, is to create an 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,
});
Here watch out: Your destination path should exist. Also dont forget an extension for your file in this case .png
Now you create your route:
const { uploadImageStorage } = require("../yourstorage")
app.post("/api/saveimage", uploadImageStorage.single("image"), (req, res) => {
let file = req.file
let path = file.path
})
Here you need to know at uploadImageStorage.single("image")
i used image
like i used it in formData.append("image", file)
they need to be the same.
Now you can save the path of your file into a database. You can also transform your image with sharp
if you want
From my experience if you have folder called static
and you have a image inside of it like photo.png
you usually get the photo with localhost:3000/photo.png
and not with localhost:3000/static/photo.png
You will need to remove static
from your path if you have this setup. Otherwise if you try to display the image on the frontend you wont see it.