expressjsHow can I use Express.js and Multer to upload files?
Express.js and Multer can be used together to upload files. Multer is a Node.js middleware for handling multipart/form-data, which is primarily used for uploading files.
Example code
const express = require('express');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
const app = express();
app.post('/upload', upload.single('myFile'), (req, res, next) => {
const file = req.file;
if (!file) {
const error = new Error('Please upload a file');
error.httpStatusCode = 400;
return next(error);
}
res.send(file);
});
This example code will create an Express.js application with a single route that will accept a single file upload. The file will be uploaded to the uploads/
directory and the file will be sent back as a response.
Code explanation
const express = require('express');
- Require the Express.js module.const multer = require('multer');
- Require the Multer module.const upload = multer({ dest: 'uploads/' });
- Create a Multer instance with the destination folder set touploads/
.app.post('/upload', upload.single('myFile'), (req, res, next) => {
- Create a POST route for/upload
and use the Multer instance to accept a single file upload namedmyFile
.const file = req.file;
- Get the file from the request.if (!file) {
- Check if a file was uploaded.res.send(file);
- Send the file back as a response.
Helpful links
More of Expressjs
- How do I set the time zone in Express.js?
- How can I use Express.js to generate a zip response?
- How do I use Yarn to add Express.js to my project?
- How do I find Express.js tutorials on YouTube?
- How can I use Node.js and Express together to create a web application?
- How can I use Express.js to yield results?
- How can I use an ExpressJS webhook to receive data from an external source?
- How can I use Express.js and Winston together to create a logging system?
- How do I use Express.js to handle x-www-form-urlencoded data?
- How can I use Express.js with TypeScript?
See more codes...