expressjs / multer

Node.js middleware for handling `multipart/form-data`.
MIT License
11.61k stars 1.06k forks source link

Upload multiple files with multer? #1272

Closed Priya-Rathor closed 2 months ago

Priya-Rathor commented 2 months ago

I just can't figured whats wrong why my codes below. I try to upload multiple files. The problem is that i had an "message": "All fields are required.".. I can make it to upload single file just fine, If I put upload.single('image') but I can't make it upload multiple files. With multiple feilds.It will take only one at a time So what's wrong?

//Route file
// routes/verifyIDRoute.js
import express from 'express';
import { upload } from '../middlewers/verifyIDMiddleware.js'; // Adjust the path as necessary
import { verifyIDUpload } from '../controllers/verifyIDController.js'; // Adjust the path as necessary

const router = express.Router();

// Define route for verifying ID
router.post('/verify', upload, verifyIDUpload);

export default router;
 controller file
// controllers/verifyIDController.js
import VerifyID from '../models/VerifyIDSchema.js';

export const verifyIDUpload = async (req, res) => {
  try {
    // Log the received body and files for debugging
    console.log('Received Request Body:', req.body);
    console.log('Received Files:', req.files);

    const { aadharNumber, panNumber } = req.body;

    // Ensure all fields are present
    if (!aadharNumber || !panNumber || !req.files['panDocument'] || !req.files['aadharDocument']) {
      console.log('Validation Failed: Missing fields or documents');
      return res.status(400).json({ message: 'All fields are required.' });
    }

    // Extract file information
    const panDocument = req.files['panDocument'][0];
    const aadharDocument = req.files['aadharDocument'][0];

    // Log file information for debugging
    console.log('PAN Document Info:', panDocument);
    console.log('Aadhar Document Info:', aadharDocument);

    // Create a new record in the database
    const newVerifyID = new VerifyID({
      aadharNumber,
      panNumber,
      panDocument: panDocument.filename,
      aadharDocument: aadharDocument.filename,
    });

    // Log the data to be saved in the database
    console.log('Data to Save:', {
      aadharNumber,
      panNumber,
      panDocument: panDocument.filename,
      aadharDocument: aadharDocument.filename,
    });

    // Save to the database
    await newVerifyID.save();

    // Log successful operation
    console.log('Documents uploaded and saved successfully!');

    res.status(200).json({ message: 'Documents uploaded successfully!' });
  } catch (error) {
    // Log error details for debugging
    console.error('Error uploading documents:', error.message);
    res.status(500).json({ message: 'Error uploading documents', error: error.message });
  }
};
Middleware file
// middlewares/verifyIDMiddleware.js
import multer from 'multer';
import path from 'path';

// Configure storage for multer
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/'); // Directory to store uploaded files
  },
  filename: (req, file, cb) => {
    const filename = `${Date.now()}${path.extname(file.originalname)}`;
    cb(null, filename); // Filename with timestamp
  },
});

// Middleware for handling file uploads
const upload = multer({
  storage,
}).fields([
  { name: 'panDocument', maxCount: 1 },
  { name: 'aadharDocument', maxCount: 1 },
]);

export { upload };
Schema file
// models/VerifyIDSchema.js
import mongoose from 'mongoose';

const verifyIDSchema = new mongoose.Schema({
  aadharNumber: {
    type: String,
    required: true,
  },
  panNumber: {
    type: String,
    required: true,
  },
  panDocument: {
    type: String,
    required: true,
  },
  aadharDocument: {
    type: String,
    required: true,
  },
}, { timestamps: true });

const VerifyID = mongoose.model('VerifyID', verifyIDSchema);

export default VerifyID;
mohamma1436 commented 2 months ago

I think you should use upload.array('files', 12) for uploading multiple files

IamLizu commented 2 months ago

Duplicate of #1274 which was later converted to a discussion: https://github.com/expressjs/multer/discussions/1275