The multer
npm package is a middleware used for handling multipart/form-data, which is primarily used for file uploads in Node.js applications. It allows you to upload files to your server with ease, making it one of the most popular file upload libraries in the Node.js ecosystem.
multer
:multipart/form-data
requests (usually form submissions containing files), making it easy to handle file uploads in your server.multer
allows you to specify where and how files should be stored, either in memory or on the disk.multer
:multer
simplifies that process.import multer from 'multer';
import { v4 as uuid } from 'uuid'; // for unique identification
multer
: This is a middleware for handling multipart/form-data
, which is commonly used for uploading files in Node.js and Express applications.uuid
: The uuid
library is used to generate unique identifiers. v4
creates a version 4 UUID, which is a universally unique identifier.const storage = multer.diskStorage({
// Define the destination folder for uploaded files
destination(req, file, callback) {
callback(null, 'uploads');
},
// Define the filename for the uploaded file
filename(req, file, callback) {
const id = uuid(); // Generate a unique ID for each file using UUID v4
const extName = file.originalname.split('.').pop(); // Extract the file extension from the original name
callback(null, `${id}.${extName}`); // Construct the new filename with the UUID and original file extension
},
});
multer.diskStorage
: This method allows you to configure how files are stored on disk.
destination
:
req
: The request object.file
: The file object representing the uploaded file.callback
: A callback function that takes two arguments: error
and destination
. In this case, callback(null, 'uploads')
specifies that files will be saved in the uploads
directory. If there were an error, you would pass an error object instead of null
.filename
:
req
: The request object.file
: The file object representing the uploaded file.callback
: A callback function that takes two arguments: error
and filename
.const id = uuid();
: Generates a unique identifier for the file using UUID v4. This ensures that each file has a unique name.const extName = file.originalname.split('.').pop();
: Extracts the file extension from the original filename. For instance, if the original file is named image.jpg
, extName
will be jpg
.callback(null,
${id}.${extName});
: Constructs the new filename using the unique ID and the original file extension. For example, if uuid()
generates 123e4567-e89b-12d3-a456-426614174000
and the original file extension is jpg
, the new filename will be 123e4567-e89b-12d3-a456-426614174000.jpg
.