In this tutorial, we will be walking you through an example of how to develop a simple express API for file upload.
Sometimes it happens while developing an express API we may need file upload functionality. Although there are several packages available for the nodejs eco-system however, for this tutorial, we will be focusing on a popular package named “express-fileupload“.
Install express-fileupload and other required nodejs packages
To upload files on the express server, we need to initialize our project using the below command.
npm init -y
Also, we have to install all the required packages for this tutorial like below.
npm install express express-fileupload
After that, create a folder in the current working directory where you want to save the uploaded files. For instance, we have named it Uploads. Then create an entry point index.js file in our root directory.
const express = require("express");
const fileUpload = require("express-fileupload");
const app = express();
app.use(fileUpload());
const PORT = 3000;
app.post("/upload", async (req, res) => {
const { files } = req;
const { sampleFile } = files;
const uploadPath = `${__dirname}/Uploads/${sampleFile.name}`;
const hasFiles = Object.keys(files).length > 0;
try {
if (!(files && hasFiles)) {
return res.status(400).send("No files were uploaded.");
}
res.send("File Uploaded Successfully!");
sampleFile.mv(uploadPath);
} catch (error) {
res.status(500).send(error);
}
});
app.listen(PORT, () => {
console.log("Server is Up running on PORT : ", PORT);
});
Afterward, files that we’ll upload, will get saved inside our Uploads directory.
Testing our API
At last, we need to test our application and for that, we have to create a simple form where we will POST our file.
<html>
<body>
<form ref='uploadForm'
id='uploadForm'
action='http://localhost:3000/upload'
method='post'
encType="multipart/form-data">
<input type="file" name="sampleFile" />
<input type='submit' value='Upload!' />
</form>
</body>
</html>
Conclusion
I want to conclude that it is super easy to upload files in nodejs. Indeed it was so much fun to make this tutorial, I enjoyed making it a lot, hope you people find it useful. Still, if you are confused, please feel free to ask in the comment section below. Also, Don’t forget to appreciate in the comment section.
THANK YOU!
One thought on “Express file upload”