I just can't figured whats wrong why my codes below. I try to upload multiple files. #1275
-
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? import express from 'express';
import multer from 'multer';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
// Recreate __dirname for ES module
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = process.env.PORT || 3000;
// Define the directories to store different uploads
const uploadDirs = {
file1: path.join(__dirname, 'uploads/file1'),
file2: path.join(__dirname, 'uploads/file2'),
file3: path.join(__dirname, 'uploads/file3'),
file4: path.join(__dirname, 'uploads/file4'),
};
// Ensure the upload directories exist
Object.values(uploadDirs).forEach((dir) => {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
console.log(`Created directory: ${dir}`); // Debugging log
} else {
console.log(`Directory already exists: ${dir}`); // Debugging log
}
});
// Configure Multer storage for different files
const storage = multer.diskStorage({
destination: (req, file, cb) => {
console.log(`Handling file destination for: ${file.fieldname}`); // Debugging log
if (file.fieldname === 'file1') {
cb(null, uploadDirs.file1);
} else if (file.fieldname === 'file2') {
cb(null, uploadDirs.file2);
} else if (file.fieldname === 'file3') {
cb(null, uploadDirs.file3);
} else if (file.fieldname === 'file4') {
cb(null, uploadDirs.file4);
} else {
console.warn(`Unexpected file field: ${file.fieldname}`); // Debugging log
cb(new Error('Unexpected file field'));
}
},
filename: (req, file, cb) => {
console.log(`Processing filename for: ${file.originalname}`); // Debugging log
cb(null, `${Date.now()}-${file.originalname}`); // Define the filename format
},
});
const upload = multer({ storage: storage });
// Endpoint to handle file uploads
app.post(
'/upload',
upload.fields([
{ name: 'file1', maxCount: 1 },
{ name: 'file2', maxCount: 1 },
{ name: 'file3', maxCount: 1 },
{ name: 'file4', maxCount: 1 },
]),
(req, res) => {
try {
// Log request body to debug form-data submission
console.log('Request body:', req.body);
console.log('Request files:', req.files); // Debugging log
const files = req.files;
if (!files) {
console.log('No files found in the request.'); // Debugging log
} else {
['file1', 'file2', 'file3', 'file4'].forEach((fieldName) => {
if (files && files[fieldName]) {
console.log(`${fieldName} Details:`, files[fieldName][0]);
console.log(
`${fieldName} uploaded: ${files[fieldName][0].originalname} -> ${files[fieldName][0].path}`
);
} else {
console.log(`${fieldName} not uploaded.`);
}
});
}
res.status(200).json({ message: 'Files uploaded successfully', files: req.files });
} catch (error) {
console.error('File upload failed:', error);
res.status(500).json({ message: 'File upload failed', error });
}
}
);
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
}); only take one image file1 Details: {
fieldname: 'file1',
originalname: 'cv4.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: 'E:\\tmp\\demo\\uploads\\file1',
filename: '1725255887575-cv4.jpg',
path: 'E:\\tmp\\demo\\uploads\\file1\\1725255887575-cv4.jpg',
size: 538005
}
destination: 'E:\\tmp\\demo\\uploads\\file1',
destination: 'E:\\tmp\\demo\\uploads\\file1',
filename: '1725255887575-cv4.jpg',
destination: 'E:\\tmp\\demo\\uploads\\file1',
destination: 'E:\\tmp\\demo\\uploads\\file1',
destination: 'E:\\tmp\\demo\\uploads\\file1',
destination: 'E:\\tmp\\demo\\uploads\\file1',
filename: '1725255887575-cv4.jpg',
path: 'E:\\tmp\\demo\\uploads\\file1\\1725255887575-cv4.jpg',
size: 538005
}
file1 uploaded: cv4.jpg -> E:\tmp\demo\uploads\file1\1725255887575-cv4.jpg
file2 not uploaded.
file3 not uploaded.
file4 not uploaded.
Handling file destination for: file3
Processing filename for: cv2.jpg
Request body: [Object: null prototype] { file4: '' }
Request files: [Object: null prototype] {
file3: [
{
fieldname: 'file3',
originalname: 'cv2.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: 'E:\\tmp\\demo\\uploads\\file3',
filename: '1725255920215-cv2.jpg',
path: 'E:\\tmp\\demo\\uploads\\file3\\1725255920215-cv2.jpg',
size: 662066
}
]
}
file1 not uploaded.
file2 not uploaded.
file3 Details: {
fieldname: 'file3',
originalname: 'cv2.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: 'E:\\tmp\\demo\\uploads\\file3',
file3 Details: {
fieldname: 'file3',
originalname: 'cv2.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: 'E:\\tmp\\demo\\uploads\\file3',
fieldname: 'file3',
originalname: 'cv2.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
destination: 'E:\\tmp\\demo\\uploads\\file3',
mimetype: 'image/jpeg',
destination: 'E:\\tmp\\demo\\uploads\\file3',
destination: 'E:\\tmp\\demo\\uploads\\file3',
filename: '1725255920215-cv2.jpg',
path: 'E:\\tmp\\demo\\uploads\\file3\\1725255920215-cv2.jpg',
size: 662066
}
file3 uploaded: cv2.jpg -> E:\tmp\demo\uploads\file3\1725255920215-cv2.jpg
file4 not uploaded. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hi 👋 The issue you're experiencing is likely due to how the form-data is being sent to the server. When you use An easy fix would be using |
Beta Was this translation helpful? Give feedback.
Hi 👋
The issue you're experiencing is likely due to how the form-data is being sent to the server. When you use
upload.fields([...])
, each file field should have its corresponding file uploaded in the request. However, if any of the fields (file1, file2, file3, or file4) are missing or empty in the request, your code might interpret that as an error.An easy fix would be using
upload.array("images", 4)
whereimages
is the field for the form-data key and it can have up-to specified number of images, in this case 4. Meaning, you can add one or two or three or four image. Then you could just simply access the files withreq.files
.