How to Upload a File in nodejs: A step by step guide
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:
- Defines storage for multer to save files on disk in the uploads directory.
- Generates unique filenames combining a timestamp and random number with the original filename.
2.Express App:
- Creates an Express app (app).
- Uses middleware:
- express.json(): parses JSON data from requests.
- cors(): potentially allows requests from other websites (CORS).
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:
- /api/file-upload: This is the URL for the upload route.
- upload.single(‘file’): This middleware from multer handles single file uploads named “file” in the request. To upload multiple files, refer to the documentation.
- (req, res) => …: This is the route handler function that executes when a POST request is made to the /api/file-upload URL.try…catch: It attempts to upload the file and sends a success response (status 200) with a message if successful.catch (error): If an error occurs during upload, it sends an error response (status 500) with the error details.
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.
image of postman extension in vscode
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:
- Install required dependencies (express, cors, multer, and nodemon).
- Configure file storage with unique filenames.
- Create an Express.js app and use middleware for JSON parsing and CORS.
- Define a route (/api/file-upload) to handle file uploads with multer.
- Implement error handling for successful uploads and potential errors.
- Start the server and test the functionality using Postman.
By following these steps, you’ve gained the ability to accept file uploads in your Node.js applications, enhancing their functionality and user experience.
Never miss an article: Sign up for our programming newsletter today!