feat: increase file upload limit from 20 to 500 with performance optimizations
Test and Lint / backend-test (push) Successful in 1m10s
Test and Lint / frontend-test (push) Successful in 2m22s
continuous-integration/drone/push Build is passing
Version and Release / version-bump (push) Successful in 37s
Version and Release / trigger-drone (push) Successful in 3s

Backend changes:
- Update multer configuration to accept up to 500 files per upload
- Implement batch processing (10 files per transaction) for better performance
- Add memory-efficient Sharp configuration for thumbnail generation
- Increase Express body parser limits to handle large payloads
- Add proper error handling and reporting for partial upload failures

Frontend changes:
- Update validation to allow 500 files maximum
- Implement chunked uploads (50 files per chunk) to prevent timeouts
- Add progress tracking with chunk information display
- Update error messages and translations (EN/DE)

Performance optimizations:
- Disable Sharp cache to prevent memory buildup
- Limit Sharp concurrency to 2 operations
- Use sequential read for large images
- Process files in database transaction batches
- Return detailed upload results including success/failure counts

This implementation ensures the application can handle large photo uploads
efficiently without running into memory or timeout issues.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-07-14 21:11:59 +02:00
parent ac48bfdd0d
commit 6906c8bcf7
6 changed files with 228 additions and 118 deletions
+3 -3
View File
@@ -125,9 +125,9 @@ const authLimiter = rateLimit({
app.use('/api/', limiter); app.use('/api/', limiter);
app.use('/api/auth', authLimiter); app.use('/api/auth', authLimiter);
// Body parsing middleware // Body parsing middleware with increased limits for large uploads
app.use(express.json()); app.use(express.json({ limit: '100mb' }));
app.use(express.urlencoded({ extended: true })); app.use(express.urlencoded({ extended: true, limit: '100mb' }));
// Maintenance mode middleware - add after body parsing but before routes // Maintenance mode middleware - add after body parsing but before routes
app.use(maintenanceMiddleware); app.use(maintenanceMiddleware);
+118 -67
View File
@@ -61,7 +61,10 @@ const { validateFileType } = require('../utils/fileSecurityUtils');
const upload = multer({ const upload = multer({
storage: storage, storage: storage,
limits: { limits: {
fileSize: 50 * 1024 * 1024, // 50MB limit fileSize: 50 * 1024 * 1024, // 50MB limit per file
files: 500, // Maximum 500 files
// Set a reasonable field size limit to prevent memory issues
fieldSize: 10 * 1024 * 1024, // 10MB for non-file fields
}, },
fileFilter: (req, file, cb) => { fileFilter: (req, file, cb) => {
// Accept images only with proper validation // Accept images only with proper validation
@@ -85,13 +88,17 @@ const validateUploadContent = createFileUploadValidator({
}); });
// Upload photos for an event // Upload photos for an event
// Increased limit to 500 files, but recommend chunked uploads for better performance
router.post('/:eventId/upload', adminAuth, (req, res, next) => { router.post('/:eventId/upload', adminAuth, (req, res, next) => {
upload.array('photos', 20)(req, res, (err) => { upload.array('photos', 500)(req, res, (err) => {
if (err) { if (err) {
console.error('Multer error:', err); console.error('Multer error:', err);
if (err instanceof multer.MulterError) { if (err instanceof multer.MulterError) {
if (err.code === 'LIMIT_FILE_SIZE') { if (err.code === 'LIMIT_FILE_SIZE') {
return res.status(400).json({ error: 'File too large. Maximum size is 50MB.' }); return res.status(400).json({ error: 'File too large. Maximum size is 50MB per file.' });
}
if (err.code === 'LIMIT_FILE_COUNT') {
return res.status(400).json({ error: 'Too many files. Maximum 500 files per upload.' });
} }
return res.status(400).json({ error: `Upload error: ${err.message}` }); return res.status(400).json({ error: `Upload error: ${err.message}` });
} }
@@ -136,90 +143,122 @@ router.post('/:eventId/upload', adminAuth, (req, res, next) => {
} }
const uploadedPhotos = []; const uploadedPhotos = [];
const errors = [];
// Process files in batches to optimize database operations
const BATCH_SIZE = 10; // Process 10 files at a time for database operations
for (let i = 0; i < req.files.length; i += BATCH_SIZE) {
const batch = req.files.slice(i, i + BATCH_SIZE);
// Start a single transaction for the batch
const trx = await db.transaction();
// Process each uploaded file
for (const file of req.files) {
let trx;
try { try {
// Start transaction for atomic counter update // Get initial counter for this batch
trx = await db.transaction(); let batchCounter = 1;
// Get and increment the counter for this category
let counter = 1;
if (category) { if (category) {
// Lock the category row and get current counter
const categoryData = await trx('photo_categories') const categoryData = await trx('photo_categories')
.where({ id: parsedCategoryId }) .where({ id: parsedCategoryId })
.forUpdate() .forUpdate()
.first(); .first();
batchCounter = (categoryData.photo_counter || 0) + 1;
counter = (categoryData.photo_counter || 0) + 1;
// Update counter
await trx('photo_categories')
.where({ id: parsedCategoryId })
.update({ photo_counter: counter });
} else { } else {
// For uncategorized photos, count existing uncategorized photos
const uncategorizedCount = await trx('photos') const uncategorizedCount = await trx('photos')
.where({ event_id: eventId }) .where({ event_id: eventId })
.whereNull('category_id') .whereNull('category_id')
.count('id as count') .count('id as count')
.first(); .first();
batchCounter = (uncategorizedCount.count || 0) + 1;
counter = (uncategorizedCount.count || 0) + 1;
} }
// Generate new filename const batchPhotos = [];
const extension = path.extname(file.originalname);
const newFilename = generatePhotoFilename(
event.event_name,
category ? category.name : 'uncategorized',
counter,
extension
);
// Rename the file for (let fileIndex = 0; fileIndex < batch.length; fileIndex++) {
const oldPath = file.path; const file = batch[fileIndex];
const newPath = path.join(path.dirname(oldPath), newFilename); const counter = batchCounter + fileIndex;
await fs.rename(oldPath, newPath);
// Update file object try {
file.filename = newFilename; // Generate new filename
file.path = newPath; const extension = path.extname(file.originalname);
const newFilename = generatePhotoFilename(
event.event_name,
category ? category.name : 'uncategorized',
counter,
extension
);
// Generate thumbnail with new filename // Rename the file
const thumbnailPath = await generateThumbnail(file.path); const oldPath = file.path;
const newPath = path.join(path.dirname(oldPath), newFilename);
await fs.rename(oldPath, newPath);
// Calculate relative paths // Update file object
const storagePath = getStoragePath(); file.filename = newFilename;
const relativePath = path.relative(path.join(storagePath, 'events/active'), file.path); file.path = newPath;
const relativeThumbPath = thumbnailPath; // thumbnailPath is already relative to storage root
// Add to database // Generate thumbnail with new filename
const [photoId] = await trx('photos').insert({ const thumbnailPath = await generateThumbnail(file.path);
event_id: eventId,
filename: file.filename,
path: relativePath,
thumbnail_path: relativeThumbPath,
category_id: parsedCategoryId || null,
type: 'individual', // Keep for backwards compatibility
size_bytes: file.size
});
// Commit transaction // Calculate relative paths
const storagePath = getStoragePath();
const relativePath = path.relative(path.join(storagePath, 'events/active'), file.path);
const relativeThumbPath = thumbnailPath;
// Prepare photo data for batch insert
batchPhotos.push({
event_id: eventId,
filename: file.filename,
path: relativePath,
thumbnail_path: relativeThumbPath,
category_id: parsedCategoryId || null,
type: 'individual',
size_bytes: file.size
});
} catch (error) {
console.error(`Error processing file ${file.originalname}:`, error);
errors.push({ filename: file.originalname, error: error.message });
// Delete the file if it was partially processed
if (file.path) {
try { await fs.unlink(file.path); } catch (e) {}
}
}
}
// Batch insert all photos from this batch
if (batchPhotos.length > 0) {
const insertedIds = await trx('photos').insert(batchPhotos).returning('id');
// Update category counter if needed
if (category) {
await trx('photo_categories')
.where({ id: parsedCategoryId })
.update({ photo_counter: batchCounter + batchPhotos.length - 1 });
}
// Add to uploaded photos array
batchPhotos.forEach((photo, index) => {
uploadedPhotos.push({
id: insertedIds[index]?.id || insertedIds[index],
filename: photo.filename,
size: photo.size_bytes,
category_id: photo.category_id
});
});
}
// Commit the batch transaction
await trx.commit(); await trx.commit();
uploadedPhotos.push({
id: photoId,
filename: file.filename,
size: file.size,
category_id: parsedCategoryId || null
});
} catch (error) { } catch (error) {
console.error(`Error processing file ${file.filename}:`, error); console.error(`Error processing batch starting at index ${i}:`, error);
if (trx) await trx.rollback(); await trx.rollback();
// Continue with other files
// Try to clean up files from failed batch
for (const file of batch) {
if (file.path) {
try { await fs.unlink(file.path); } catch (e) {}
}
}
} }
} }
@@ -230,10 +269,22 @@ router.post('/:eventId/upload', adminAuth, (req, res, next) => {
{ type: 'admin', id: req.admin.id, name: req.admin.username } { type: 'admin', id: req.admin.id, name: req.admin.username }
); );
res.json({ // Prepare response
const response = {
message: `Successfully uploaded ${uploadedPhotos.length} photos`, message: `Successfully uploaded ${uploadedPhotos.length} photos`,
photos: uploadedPhotos photos: uploadedPhotos,
}); totalFiles: req.files.length,
successCount: uploadedPhotos.length,
failureCount: errors.length
};
// Include error details if any files failed
if (errors.length > 0) {
response.errors = errors;
response.message = `Uploaded ${uploadedPhotos.length} of ${req.files.length} photos. ${errors.length} failed.`;
}
res.json(response);
} catch (error) { } catch (error) {
console.error('Error uploading photos:', error); console.error('Error uploading photos:', error);
res.status(500).json({ error: 'Failed to upload photos' }); res.status(500).json({ error: 'Failed to upload photos' });
+25 -8
View File
@@ -2,6 +2,10 @@ const sharp = require('sharp');
const path = require('path'); const path = require('path');
const fs = require('fs').promises; const fs = require('fs').promises;
// Configure sharp for better memory management with large batches
sharp.cache(false); // Disable cache to prevent memory buildup
sharp.concurrency(2); // Limit concurrent operations
const THUMBNAIL_WIDTH = 300; const THUMBNAIL_WIDTH = 300;
const getStoragePath = () => process.env.STORAGE_PATH || path.join(__dirname, '../../../storage'); const getStoragePath = () => process.env.STORAGE_PATH || path.join(__dirname, '../../../storage');
const getThumbnailPath = () => path.join(getStoragePath(), 'thumbnails'); const getThumbnailPath = () => path.join(getStoragePath(), 'thumbnails');
@@ -15,16 +19,29 @@ async function generateThumbnail(imagePath) {
// Ensure thumbnail directory exists // Ensure thumbnail directory exists
await fs.mkdir(thumbnailDir, { recursive: true }); await fs.mkdir(thumbnailDir, { recursive: true });
// Generate thumbnail try {
await sharp(imagePath) // Generate thumbnail with memory-efficient settings
.resize(THUMBNAIL_WIDTH, null, { await sharp(imagePath, {
withoutEnlargement: true, limitInputPixels: 268402689, // ~16k x 16k max
fit: 'inside' sequentialRead: true // More memory efficient for large images
}) })
.jpeg({ quality: 80 }) .resize(THUMBNAIL_WIDTH, null, {
.toFile(thumbnailPath); withoutEnlargement: true,
fit: 'inside'
})
.jpeg({
quality: 80,
progressive: true, // Progressive JPEG for better loading
mozjpeg: true // Better compression
})
.toFile(thumbnailPath);
return path.relative(getStoragePath(), thumbnailPath); return path.relative(getStoragePath(), thumbnailPath);
} catch (error) {
console.error(`Failed to generate thumbnail for ${filename}:`, error);
// Return null if thumbnail generation fails, don't fail the whole upload
return null;
}
} }
module.exports = { generateThumbnail }; module.exports = { generateThumbnail };
+70 -31
View File
@@ -18,6 +18,8 @@ export const PhotoUpload: React.FC<PhotoUploadProps> = ({ eventId, onUploadCompl
const [isUploading, setIsUploading] = useState(false); const [isUploading, setIsUploading] = useState(false);
const [selectedFiles, setSelectedFiles] = useState<File[]>([]); const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
const [uploadProgress, setUploadProgress] = useState(0); const [uploadProgress, setUploadProgress] = useState(0);
const [currentChunk, setCurrentChunk] = useState(0);
const [totalChunks, setTotalChunks] = useState(0);
const [selectedCategoryId, setSelectedCategoryId] = useState<number | null>(null); const [selectedCategoryId, setSelectedCategoryId] = useState<number | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null); const fileInputRef = useRef<HTMLInputElement>(null);
@@ -35,13 +37,13 @@ export const PhotoUpload: React.FC<PhotoUploadProps> = ({ eventId, onUploadCompl
// Check total file count with existing files // Check total file count with existing files
const totalFiles = selectedFiles.length + imageFiles.length; const totalFiles = selectedFiles.length + imageFiles.length;
if (totalFiles > 20) { if (totalFiles > 500) {
const allowedNewFiles = 20 - selectedFiles.length; const allowedNewFiles = 500 - selectedFiles.length;
if (allowedNewFiles <= 0) { if (allowedNewFiles <= 0) {
toast.error(t('upload.maxFilesReached') || 'Maximum 20 files allowed'); toast.error(t('upload.maxFilesReached') || 'Maximum 500 files allowed');
return; return;
} }
toast.warning(t('upload.someFilesSkipped') || `Only ${allowedNewFiles} more files can be added (20 max)`); toast.warning(t('upload.someFilesSkipped') || `Only ${allowedNewFiles} more files can be added (500 max)`);
setSelectedFiles(prev => [...prev, ...imageFiles.slice(0, allowedNewFiles)]); setSelectedFiles(prev => [...prev, ...imageFiles.slice(0, allowedNewFiles)]);
return; return;
} }
@@ -57,42 +59,62 @@ export const PhotoUpload: React.FC<PhotoUploadProps> = ({ eventId, onUploadCompl
if (selectedFiles.length === 0) return; if (selectedFiles.length === 0) return;
// Validate file count // Validate file count
if (selectedFiles.length > 20) { if (selectedFiles.length > 500) {
toast.error(t('upload.tooManyFiles') || 'Maximum 20 files can be uploaded at once'); toast.error(t('upload.tooManyFiles') || 'Maximum 500 files can be uploaded at once');
return; return;
} }
setIsUploading(true); setIsUploading(true);
setUploadProgress(0); setUploadProgress(0);
const formData = new FormData(); // For large uploads, chunk the files to prevent memory issues
selectedFiles.forEach((file, index) => { const CHUNK_SIZE = 50; // Upload 50 files at a time
console.log(`Adding file ${index}: ${file.name}, size: ${file.size}`); const chunks = [];
formData.append('photos', file);
});
if (selectedCategoryId) { for (let i = 0; i < selectedFiles.length; i += CHUNK_SIZE) {
formData.append('category_id', selectedCategoryId.toString()); chunks.push(selectedFiles.slice(i, i + CHUNK_SIZE));
} }
// Debug: Log FormData contents setTotalChunks(chunks.length);
console.log('FormData entries:'); let totalUploaded = 0;
for (let pair of formData.entries()) { let failedFiles = [];
console.log(pair[0], pair[1]);
}
try { try {
const response = await api.post(`/admin/events/${eventId}/upload`, formData, { for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {
// Don't set Content-Type header - axios will set it with the boundary setCurrentChunk(chunkIndex + 1);
onUploadProgress: (progressEvent) => { const chunk = chunks[chunkIndex];
if (progressEvent.total) { const formData = new FormData();
const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
setUploadProgress(progress);
}
},
});
console.log('Upload result:', response.data); chunk.forEach((file) => {
formData.append('photos', file);
});
if (selectedCategoryId) {
formData.append('category_id', selectedCategoryId.toString());
}
try {
const response = await api.post(`/admin/events/${eventId}/upload`, formData, {
onUploadProgress: (progressEvent) => {
if (progressEvent.total) {
// Calculate overall progress across all chunks
const chunkProgress = progressEvent.loaded / progressEvent.total;
const overallProgress = ((chunkIndex + chunkProgress) / chunks.length) * 100;
setUploadProgress(Math.round(overallProgress));
}
},
});
totalUploaded += chunk.length;
console.log(`Chunk ${chunkIndex + 1}/${chunks.length} uploaded:`, response.data);
} catch (error: any) {
console.error(`Error uploading chunk ${chunkIndex + 1}:`, error);
failedFiles.push(...chunk.map(f => f.name));
// Continue with next chunk even if one fails
continue;
}
}
// Clear selected files // Clear selected files
setSelectedFiles([]); setSelectedFiles([]);
@@ -100,8 +122,15 @@ export const PhotoUpload: React.FC<PhotoUploadProps> = ({ eventId, onUploadCompl
fileInputRef.current.value = ''; fileInputRef.current.value = '';
} }
// Show success message // Show appropriate message
toast.success(t('toast.uploadSuccess')); if (failedFiles.length === 0) {
toast.success(t('upload.uploadComplete') || `Successfully uploaded ${totalUploaded} files`);
} else {
toast.warning(
t('upload.someFilesFailed') ||
`Uploaded ${totalUploaded} files. ${failedFiles.length} files failed.`
);
}
// Call callback // Call callback
if (onUploadComplete) { if (onUploadComplete) {
@@ -113,6 +142,8 @@ export const PhotoUpload: React.FC<PhotoUploadProps> = ({ eventId, onUploadCompl
} finally { } finally {
setIsUploading(false); setIsUploading(false);
setUploadProgress(0); setUploadProgress(0);
setCurrentChunk(0);
setTotalChunks(0);
} }
}; };
@@ -223,7 +254,10 @@ export const PhotoUpload: React.FC<PhotoUploadProps> = ({ eventId, onUploadCompl
{isUploading && ( {isUploading && (
<div className="mt-4"> <div className="mt-4">
<div className="flex justify-between text-sm text-neutral-600 mb-1"> <div className="flex justify-between text-sm text-neutral-600 mb-1">
<span>{t('upload.uploading')}</span> <span>
{t('upload.uploading')}
{totalChunks > 1 && ` (${t('common.chunk') || 'Chunk'} ${currentChunk}/${totalChunks})`}
</span>
<span>{uploadProgress}%</span> <span>{uploadProgress}%</span>
</div> </div>
<div className="w-full bg-neutral-200 rounded-full h-2"> <div className="w-full bg-neutral-200 rounded-full h-2">
@@ -232,6 +266,11 @@ export const PhotoUpload: React.FC<PhotoUploadProps> = ({ eventId, onUploadCompl
style={{ width: `${uploadProgress}%` }} style={{ width: `${uploadProgress}%` }}
/> />
</div> </div>
{totalChunks > 1 && (
<p className="text-xs text-neutral-500 mt-1">
{t('upload.uploadingChunks') || `Uploading ${selectedFiles.length} files in ${totalChunks} batches...`}
</p>
)}
</div> </div>
)} )}
</div> </div>
+4 -1
View File
@@ -47,7 +47,10 @@
"uploadComplete": "Upload abgeschlossen!", "uploadComplete": "Upload abgeschlossen!",
"uploadFailed": "Upload fehlgeschlagen", "uploadFailed": "Upload fehlgeschlagen",
"someFilesFailed": "Einige Dateien konnten nicht hochgeladen werden", "someFilesFailed": "Einige Dateien konnten nicht hochgeladen werden",
"uploadPhotos": "Fotos hochladen" "uploadPhotos": "Fotos hochladen",
"maxFilesReached": "Maximal 500 Dateien erlaubt",
"someFilesSkipped": "Einige Dateien wurden übersprungen (500 Dateien Limit)",
"tooManyFiles": "Maximal 500 Dateien können gleichzeitig hochgeladen werden"
}, },
"navigation": { "navigation": {
"dashboard": "Dashboard", "dashboard": "Dashboard",
+3 -3
View File
@@ -48,9 +48,9 @@
"uploadFailed": "Upload failed", "uploadFailed": "Upload failed",
"someFilesFailed": "Some files failed to upload", "someFilesFailed": "Some files failed to upload",
"uploadPhotos": "Upload Photos", "uploadPhotos": "Upload Photos",
"maxFilesReached": "Maximum 20 files allowed", "maxFilesReached": "Maximum 500 files allowed",
"someFilesSkipped": "Some files were skipped (20 file limit)", "someFilesSkipped": "Some files were skipped (500 file limit)",
"tooManyFiles": "Maximum 20 files can be uploaded at once" "tooManyFiles": "Maximum 500 files can be uploaded at once"
}, },
"navigation": { "navigation": {
"dashboard": "Dashboard", "dashboard": "Dashboard",