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 themultermodule.const upload = multer({ dest: 'uploads/' });- Initialize themultermiddleware with thedestoption set touploads/.app.post('/upload', upload.single('myFile'), (req, res) => {- Create a route that will handle the file upload, using theupload.single()method with themyFileparameter.const file = req.file;- Access the file that was uploaded.
Helpful links
- Multer - npm package for handling multipart/form-data.
More of Expressjs
- How do I find Express.js tutorials on YouTube?
- How do I download a zip file using Express.js?
- How can I use Zipkin to trace requests in Express.js?
- How do I use Zod with Express.js?
- How do I use Express.js to parse YAML files?
- How can I disable the X-Powered-By header in Express.js?
- How can I make an XHR request using Express.js?
- How do I implement CSRF protection in an Express.js application?
- How can I use the x-forwarded-for header in Express.js?
- How can I use Express.js to implement websockets in my application?
See more codes...