expressjsHow do I upload a file using Express.js?
To upload a file using Express.js, you can use the multer
middleware. It is a node.js middleware for handling multipart/form-data, which is primarily used for uploading files.
Here is an example of how to use multer
:
// Require the multer module
const multer = require('multer');
// Initialize the multer middleware
const upload = multer({ dest: 'uploads/' });
// Create a route that will handle the file upload
app.post('/upload', upload.single('myFile'), (req, res) => {
// Access the file that was uploaded
const file = req.file;
console.log(file);
/*
Output:
{
fieldname: 'myFile',
originalname: 'example.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: 'uploads/',
filename: 'd78c2acfb3f3a08d2a9f3c2cacb6e3f8',
path: 'uploads/d78c2acfb3f3a08d2a9f3c2cacb6e3f8',
size: 955941
}
*/
});
The multer
middleware will parse the multipart/form-data request, and store the file in the directory specified by the dest
option. The req.file
object will contain information about the uploaded file.
Code explanation
const multer = require('multer');
- Require themulter
module.const upload = multer({ dest: 'uploads/' });
- Initialize themulter
middleware with thedest
option set touploads/
.app.post('/upload', upload.single('myFile'), (req, res) => {
- Create a route that will handle the file upload, using theupload.single()
method with themyFile
parameter.const file = req.file;
- Access the file that was uploaded.
Helpful links
- Multer - npm package for handling multipart/form-data.
More of Expressjs
- How can I use express-zip js to zip and download files?
- How can I use Express.js to create a query?
- How do I set the time zone in Express.js?
- How do I set up a YAML configuration file for a Node.js Express application?
- How do I use Zod with Express.js?
- How can I use Express.js with TypeScript?
- How do I find Express.js tutorials on YouTube?
- What are some of the best alternatives to Express.js for web development?
- How can I set up X-Frame-Options in ExpressJS?
- How can I use Express.js and Nest.js together to create a web application?
See more codes...