In this tutorial, we are going to walk through the process of creating an image file upload functionality in nodejs using multer and mkdirp package.
Note
This tutorial assumes you are familiar with express and nodejs and that you have your expressjs application up and running if not please refer to the article here
Steps
1.Install the following packages multer for file upload and mkdirp for creating multilevel directories.
2.We will create two files multer-config.js and fileupload.route.js.
multer-config.js
This is a middleware that will contain the logic for uploading an image. This middleware makes use of the mkdirp package to create the path to where the image file will be stored. We also added a fileFilter function to check that the file to be uploaded is an image
const multer = require("multer");
const mkdirp = require("mkdirp");
const MIME_TYPES = {
"image/jpg": "jpg",
"image/jpeg": "jpg",
"image/png": "png",
"image/gif": "gif",
};
const dir = "public/storeowners/uploads/images";
const storage = multer.diskStorage({
destination: (req, file, callback) => {
mkdirp(dir)
.then((data) => callback(null, dir))
.catch((e) => callback(e, dir));
},
filename: (req, file, callback) => {
const name = file.originalname.split(" ").join("_");
const extension = MIME_TYPES[file.mimetype];
callback(null, Date.now() + "." + extension);
},
});
const fileFilter = (req, file, cb) => {
if (!MIME_TYPES[file.mimetype]) {
cb("File must be an image", false);
} else {
cb(null, true);
}
};
module.exports = multer({
storage: storage,
limit: {
fileSize: 2000000,
},
fileFilter,
}).single("image");
fileupload.route.js
This will contain the route for handling http request from the client.
const express = require("express");
const router = express.Router();
const uploadImage = require("./multer-config.js"); //import the multerconfig
//create a post route to handle http request for file upload
router.post("/", uploadImage, (req, res) => {
if (req.file) {
return res.status(200).json({
success: true,
message: "Image uploaded!",
});
}
return res.status(400).json({
success: false,
error: "Image upload failed!",
});
});
module.exports = router;
App.js
This the entry point of our application, here we would do the final setup to ensure the application is working
const express = require("express");
const app = express();
//import the fileupload route
const fileuploadRoute = require("./fileupload.route.js");
const cors = require("cors");
app.use(cors());
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(express.static("./public"));
//setup the file upload route
app.use("/api/uploadimage", fileuploadRoute);
//start listen on port 3000 or any port you prefer
app.listen(3000, () => {
console.log("server is listening on port 3000");
});
Now we can make a post request to the endpoint to upload your image file
localhost:3000/api/uploadimage
Happy Coding
Top comments (2)
Thanks alot for this
This helped a lot. Thanks