How to Upload a File in nodejs: A step by step guide
Luqman Shaban
Building AI-Driven Micro-SaaS & Web Apps | Founder @ Tanelt | Automating & Scaling Businesses
Introduction
Hi there! In this article we will delve into file handling in a nodejs server. We'll briefly discuss a simple way to upload file or images in using multer. A package that streamlines the file uploading process in nodejs application. To get started, initialize a nodejs app and install the following packages:
npm i express nodemon cors multer
Once the installation is complete, make sure to modify your package.json file by adding: "type": "module", and "start" : "nodemon index.js".
Your package.json file should like something like this
{
"name": "file-upload",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.19.2",
"multer": "^1.4.5-lts.1",
"nodemon": "^3.1.0"
}
}
Create a folder named upload in the root folder.
The next step will be creating index.js file (in the root folder) and importing the libraries we just installed.
import express from 'express'
import cors from 'cors'
import multer from 'multer'
We'll then create instances:
const upload = multer({ storage: storage })
const app = express()
app.use(express.json())
app.use(cors())
This code sets up file uploads and a basic Express app:
1.File Storage:
2.Express App:
- Creates an Express app (app).
- Uses middleware:
Now let's create an endpoint that will accept file uploads and pass the multer middleware to it.
app.post('/api/file-upload', upload.single('file'), (req, res) => {
try {
res.status(200).json({ success: "file upload successful" })
} catch (error) {
res.status(500).json({ error: error })
}
})
This code defines a route for uploading files:
To starts the Express.js application and make it listen for incoming requests, add the following line of code:
app.listen(4000, () => console.log('RUNNING ON PORT 4000'))
Your index.js file should now be similar to this:
import express from 'express'
import cors from 'cors'
import multer from 'multer'
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'uploads/')
},
filename: function(req, file, cb) {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
cb(null, uniqueSuffix+file.originalname)
}
})
const upload = multer({ storage: storage })
const app = express()
app.use(express.json())
app.use(cors())
app.post('/api/file-upload', upload.single('file'), (req, res) => {
try {
res.status(200).json({ success: "file upload successful" })
} catch (error) {
res.status(500).json({ error: error })
}
})
app.listen(4000, () => console.log('RUNNING ON PORT 4000'))
Open your terminal and run:
npm start
If everything went right, it should log: RUNNING ON PORT 4000.
To confirm that the code works as intended, we'll test the API on postman. Open the app or it's VsCode extension.
select Body, check form-data and make sure the key's name is file of type file. Upload your file or image then click send.
You should see:
{
"success": "file upload successful"
}
Indicating that the file has been uploaded. If you navigate to the upload folder we created earlier, you should see the file or image in there. And that's it, you have successfully implemented the uploading feature in Node.js.
Conclusion
This article has successfully guided you through setting up file uploads in a Node.js application using the multer package. You learned how to:
By following these steps, you've gained the ability to accept file uploads in your Node.js applications, enhancing their functionality and user experience.
Ready to take your Node.js skills to the next level? Sign up for our newsletter to receive updates on new articles and stay ahead of the curve in the exciting world of Node.js development!