upload file in node
To upload a file in Node.js, you can follow these steps:
- Import the necessary modules: First, you need to import the required modules. You will need the
fs
module to work with the file system and themulter
module to handle file uploads.
const fs = require('fs');
const multer = require('multer');
- Set up storage configuration: Next, you need to define the storage configuration for uploaded files. This includes specifying the destination folder where the files will be saved and the filename of the uploaded file.
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
cb(null, file.originalname);
}
});
In this example, the files will be saved in the uploads/
folder with their original filenames.
- Create a multer instance: After setting up the storage configuration, you need to create a multer instance by passing the storage configuration to it.
const upload = multer({ storage: storage });
- Define the upload route: Now, you can define the route that will handle the file upload. Use the
upload
middleware to handle the file upload and save it to the specified destination folder.
app.post('/upload', upload.single('file'), function (req, res, next) {
// File has been uploaded and saved successfully
res.send('File uploaded');
});
In this example, the route /upload
handles the file upload. The upload.single('file')
middleware specifies that only one file with the field name file
will be uploaded.
- Start the server: Finally, start the server and listen for incoming requests.
app.listen(3000, function () {
console.log('Server listening on port 3000');
});
Make sure to replace 3000
with the desired port number.
That's it! With these steps, you can upload files in Node.js using the multer
module.