Creating a File Upload Service with Node.js

Illustration of a cloud upload icon with bold text that reads "UPLOAD FILES USING NODEJS + MULTER" on a gradient pink background.

Uploading files is a fundamental feature in many web applications. Whether you need to upload images, videos, or documents, Node.js provides a robust backend for handling file uploads efficiently. In this blog, we will explore how to create a file upload service using Node.js and the Multer middleware.

Why Use Multer for File Uploads?

Multer is a middleware for handling multipart/form-data, the encoding used for file uploads in HTML forms. It makes handling files in Node.js applications easy and efficient by storing them in memory or a specified directory.

Features of Multer:

Supports single and multiple file uploads

Handles file validation and filtering

Stores files on disk or memory

Works seamlessly with Express.js

Setting Up the Projec

Step 1: Initialize a Node.js Project

First, create a new project and install the necessary dependencies:

mkdir file-upload-service

cd file-upload-service

npm init -y

npm install express multer cors

Step 2: Create an Express Server

Create a new file server.js and set up a basic Express server:

const express = require(\’express\’);

const multer = require(\’multer\’);

const cors = require(\’cors\’);

const path = require(\’path\’);

const app = express();

app.use(cors());

const upload = multer({ dest: \’uploads/\’ });

app.post(\’/upload\’, upload.single(\’file\’), (req, res) => {

if (!req.file) {

return res.status(400).send({ message: \’No file uploaded\’ });

}

res.send({ message: \’File uploaded successfully\’, filename: req.file.filename });

});

app.listen(3000, () => console.log(\’Server started on port 3000\’));

Step 3: Configuring Multer for Custom Storage

By default, Multer saves files with random names. To customize storage and file naming, use multer.diskStorage():

const storage = multer.diskStorage({

destination: \’uploads/\’,

filename: (req, file, cb) => {

cb(null, file.fieldname + \’-\’ + Date.now() + path.extname(file.originalname));

}

});

const upload = multer({

storage: storage,

limits: { fileSize: 5 * 1024 * 1024 }, // 5MB limit

fileFilter: (req, file, cb) => {

const allowedTypes = /jpeg|jpg|png|gif/;

const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());

const mimetype = allowedTypes.test(file.mimetype);

if (extname && mimetype) {

return cb(null, true);

} else {

cb(new Error(\’Only images are allowed\’));

}

}

});

Now update the /upload route to use the new configuration:

app.post(\’/upload\’, upload.single(\’image\’), (req, res) => {

if (!req.file) {

return res.status(400).send({ message: \’No file uploaded\’ });

}

res.send({ message: \’File uploaded successfully\’, filename: req.file.filename });

});

Step 4: Testing the File Upload

You can test the API using Postman:

Set the request type to POST

Enter http://localhost:3000/upload as the URL

Select Body > form-data

Add a key named image and select a file to upload

Click Send and check the response

Step 5: Serving Uploaded Files

To make uploaded files accessible, modify the Express server:

app.use(\’/uploads\’, express.static(\’uploads\’));

Now, uploaded files can be accessed via http://localhost:3000/uploads/filename.

Conclusion

Creating a file upload service in Node.js is straightforward with Multer. This guide covered setting up an Express server, handling file uploads, applying storage configurations, and serving uploaded files. You can enhance this service further by integrating cloud storage solutions like AWS S3 or Google Cloud Storage.

If you are looking for any services related to Website Development, App Development, Digital Marketing and SEO, just email us atย nchouksey@manifestinfotech.comย or Skype id:ย live:76bad32bff24d30d

๐…๐จ๐ฅ๐ฅ๐จ๐ฐ ๐”๐ฌ:

๐‹๐ข๐ง๐ค๐ž๐๐ข๐ง:ย linkedin.com/company/manifestinfotech

๐…๐š๐œ๐ž๐›๐จ๐จ๐ค:ย facebook.com/manifestinfotech/

๐ˆ๐ง๐ฌ๐ญ๐š๐ ๐ซ๐š๐ฆ:ย instagram.com/manifestinfotech/

๐“๐ฐ๐ข๐ญ๐ญ๐ž๐ซ:ย twitter.com/Manifest_info

#NodeJS #Multer #FileUpload #WebDevelopment #ExpressJS #Backend #API