Actually stuck by days figuring out how to upload multiple file using dropzone.js to mongodb using express.js and multer, tried googling all sort of ways still stucked help me.
Here is my template ejs
<form id="myDropzone" data-dropzone="data-dropzone">
<div class="fallback">
<input type="file" name="file" multiple />
</div>
<button
type="submit"
id="upload-button"
class="btn btn-primary"
>
Upload
</button>
</form>
Here is script dropzone options
// Configuration options for Dropzone
Dropzone.options.myDropzone = {
url: '/upload-multiple', // Endpoint for handling multiple file uploads
paramName: 'files', // The name of the parameter that contains the files
method: 'post',
uploadMultiple: true,
maxFiles: 5, // Maximum number of files allowed
parallelUploads: 1,
acceptedFiles: '.jpg, .jpeg, .png, .gif', // Allowed file types
autoProcessQueue: false, // Manual file uploads
init: function () {
this.on('addedfile', function (file) {
// File added callback
console.log('Files added');
});
this.on('complete', function (file) {
console.log('Files completed');
});
// Add more event listeners or custom logic as needed
}
};
Here is my app.js
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const { render } = require('ejs');
const multer = require('multer');
const path = require('path');
const mongoURI = 'mongodb://localhost:27017/sessions';
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
//init mongoose
main().catch(err => console.log(err));
async function main() {
await mongoose.connect('mongodb://localhost:27017/pblakmnsDB');
}
// Define a schema for your model (e.g., for storing file metadata)
const FileSchema = new mongoose.Schema({
filename: String,
path: String
});
const File = mongoose.model('File', FileSchema);
// Configure Multer for file upload
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/');
},
filename: (req, file, cb) => {
cb(null, file.originalname);
}
});
const upload = multer({ storage: storage });
app.post('/upload', upload.array('file', 10), async (req, res) => {
const { files } = req;
try {
const savedFiles = await Promise.all(
files.map(async file => {
const newFile = new File({
filename: file.originalname,
path: file.path
});
return await newFile.save();
})
);
if (savedFiles.length > 0) {
res.send(`Uploaded ${savedFiles.length} file(s) successfully.`);
} else {
res.status(400).send('No files were uploaded.');
}
} catch (error) {
console.error('Error uploading files:', error);
res.status(500).send('Failed to upload data to the server');
}
});
expected to uplaod multiple file using dropzone js into mongodb using express js