Here, we will write a program to upload a file in node js. We will use multer library to perform the function.
app.js file
const multer = require('multer');
const express = require('express');
const ejs = require('ejs');
const app = express();
app.set('view engine', 'ejs')
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/uploads/') // specify the directory where uploaded files will be saved
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname) // specify the filename format
}
});
const upload = multer({ storage: storage });
app.get('/upload', function(req, res) {
res.render('upload.ejs');
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
app.post('/upload', upload.single('file'), function(req, res) {
res.send('File uploaded successfully!');
});
upload.ejs file in views directory
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
</body>
</html>