What is @types/multer?
The @types/multer package provides TypeScript type definitions for Multer, a node.js middleware for handling multipart/form-data, primarily used for uploading files. It allows developers to use Multer in TypeScript projects with type checking, enabling better development experience and error handling.
What are @types/multer's main functionalities?
File Upload
This feature allows for the uploading of files. The code sample demonstrates how to set up a simple file upload endpoint using Express and Multer, where files are saved to the 'uploads/' directory.
import express from 'express';
import multer from 'multer';
const upload = multer({ dest: 'uploads/' });
const app = express();
app.post('/upload', upload.single('file'), function (req, res) {
console.log(req.file);
res.send('File uploaded successfully.');
});
Multiple Files Upload
This feature supports the uploading of multiple files in a single request. The code sample shows how to configure an endpoint to accept a maximum of 5 files using the `upload.array` method.
import express from 'express';
import multer from 'multer';
const upload = multer({ dest: 'uploads/' });
const app = express();
app.post('/upload', upload.array('files', 5), function (req, res) {
console.log(req.files);
res.send('Files uploaded successfully.');
});
File Filtering
This feature allows for filtering files based on specific criteria, such as file type. The code sample demonstrates how to accept only JPEG files using a custom file filter.
import express from 'express';
import multer from 'multer';
const fileFilter = (req, file, cb) => {
if (file.mimetype === 'image/jpeg') {
cb(null, true);
} else {
cb(new Error('Only JPEG files are allowed!'), false);
}
};
const upload = multer({ dest: 'uploads/', fileFilter });
const app = express();
app.post('/upload', upload.single('file'), function (req, res) {
res.send('File uploaded successfully.');
});
Other packages similar to @types/multer
formidable
Formidable is a Node.js module for parsing form data, especially file uploads. It differs from Multer in that it's lower level, providing a more flexible API for parsing incoming form data, including file uploads, but requires more setup compared to Multer.
busboy
Busboy is a fast, streaming parser for HTML form data for Node.js, focusing on performance. It's similar to Multer in handling file uploads but is more stream-oriented, making it suitable for handling large files or high volumes of data efficiently.