Every developer will at some point want to upload images to their backend, in this article, you'll discover the simplest way to do it in nodejs
1. What do we need?
All you need to handle images in nodejs is a package called "Multer".
Multer is a node.js middleware for handling multipart/form-data, which is primarily uploading files
You can install multer by running the command below
npm install multer
2. How do we set up and use Multer
It's easy, but first, it's important to understand that a photo is not like other forms of data you have probably been sharing, instead of JSON data, we will be sending 'form-data', we take the file, grab its binary data and send it to the server.
So create a server.js
into which we import multer like so at the top where we import express
for creating the express app.
const multer = require("multer");
const express = require("express");
const app = express();
Next, we need to set up a file storage engine where we specify the destination of the file, in this case, it's "images".
const fileStorageEngine = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "images");
},
filename: (req, file, cb) => {
cb(null, file.originalname);
},
});
const upload = multer({ storage: fileStorageEngine });
The destination folder should be existing in your project folder (or src folder)
4. Set up a post route
We create the route route as usual, but then add upload
as a middleware onto which we tuck or call a single
function (for this case we are uploading a single image at a time, we would use array
for many) with a string, "image" for this case
app.post("/single", upload.single("image"), (req, res) => {
res.send()
});
The string we pass in single works as the key for our form-data and therefore it must match.
The last piece is to have the server ready
app.listen(port, () => console.log("server started"));
5. The full code so far
const multer = require("multer");
const express = require("express");
const app = express();
const fileStorageEngine = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "images");
},
filename: (req, file, cb) => {
cb(null, file.originalname);
},
});
const upload = multer({ storage: fileStorageEngine });
app.post("/single", upload.single("image"), (req, res) => {
res.send()
});
app.listen(port, () => console.log("server started"));
Now if you head to postman and try posting photos to the route, you should notice photos added to your images folder
At this point, since multer is already working, I decided the next steps should be in another article for those that may need it.
if you found this article helpful or you may be interested in the next part, consider giving me feedback and also subscribe to my newsletter so you do not miss out on the other articles once they are released, thank you very much.