4.5 KiB
4.5 KiB
multer https://blog.logrocket.com/multer-nodejs-express-upload-file/
- By default express dont support files in formdata so we need this module
const multer = require('multer');
const app = express();
// Create a multer instance and specify destination for uploaded files
const upload = multer({ dest: 'uploads/' });
// Handle form data and file uploads using multer middleware
app.post('/submit-form', upload.single('fileInput'), (req, res) => {
// Access form data from req.body
const formData = req.body;
// Access uploaded file details from req.file
const uploadedFile = req.file;
// Process the form data and uploaded file
// ...
// Send a response
res.send('File uploaded and form data received.');
});
// Start the server
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
req.file is js object like this
{
fieldname: 'file', // Name of the form field specified in HTML
originalname: 'photo.jpg', // Name of the file on the user's computer
encoding: '7bit', // Encoding type of the file
mimetype: 'image/jpeg', // The MIME type of the file
destination: 'uploads/', // The folder where the file has been saved
filename: '1714632000-photo.jpg', // The name of the file within the destination
path: 'uploads/1714632000-photo.jpg', // The full path to the uploaded file
size: 354612 // Size of the file in bytes
}
- For multiple file uploads
app.post('/submit-form', upload.array('fileInputs', 3), (req, res) => {
// Access form data from req.body
const formData = req.body;
// Access uploaded files details from req.files
const uploadedFiles = req.files;
- For dynamic file fieldname
app.post('/submit-form', upload.any(), (req, res) => {
// Access form data from req.body
const formData = req.body;
// Access uploaded files details from req.files
const uploadedFiles = req.files;
Here 2nd argument in upload.array() ie 3 is optional. fileInputs is required name which is name of field containing files
-
Frontend part
<body> <div class="container"> <h1>File Upload</h1> <form id='form'> <div class="input-group"> <label for='name'>Your name</label> <input name='name' id='name' placeholder="Enter your name" /> </div> <div class="input-group"> <label for='files'>Select files</label> <input id='files' type="file" multiple> </div> <button class="submit-btn" type='submit'>Upload</button> </form> </div> <script src='./script.js'></script> </body>/* style.css */ body { background-color: rgb(6, 26, 27); } * { box-sizing: border-box; } .container { max-width: 500px; margin: 60px auto; } .container h1 { text-align: center; color: white; } form { background-color: white; padding: 30px; } form .input-group { margin-bottom: 15px; } form label { display: block; margin-bottom: 10px; } form input { padding: 12px 20px; width: 100%; border: 1px solid #ccc; } .submit-btn { width: 100%; border: none; background: rgb(37, 83, 3); font-size: 18px; color: white; border-radius: 3px; padding: 20px; text-align: center; }// script.js const form = document.getElementById("form"); form.addEventListener("submit", submitForm); function submitForm(e) { e.preventDefault(); const name = document.getElementById("name"); const files = document.getElementById("files"); const formData = new FormData(); formData.append("name", name.value); for(let i =0; i < files.files.length; i++) { formData.append("files", files.files[i]); } fetch("http://localhost:5000/upload_files", { method: 'POST', body: formData, headers: { "Content-Type": "multipart/form-data" } }) .then((res) => console.log(res)) .catch((err) => ("Error occured", err)); }or using just javascript instead of form element in html
const files = document.getElementById("files").files; const formData = new FormData(); files.forEach((file) => { formData.append("fileInputs", file); // Append files to the FormData object }); // this header // "content-type" : "multipart/form-data" // can cause error so if that occurs dont include this header