your file input change listener and the consequent function does not seem to care that there might have already been files uploadsd?
Jun 14, 2023
1
Level 1
How to submit multiple images with drag and drop and Larvel
Hi,
I am working with multiple images upload with drag and drop and laravel.
My issue is uploading works fine , when I select images using contol+Select-multiple images. when selct images one by one or drag images one by one only lasst image is uploading.
This is my script and html section for Drag and Drop.
HTML
`<div id="drop-zone" class="drop-zone">
<input type="file" id="file-input" multiple name="img[]">
<h3><i class="bi bi-cloud-arrow-up-fill"></i></h3>
<p for="file-input" class="drop-zone-label">Drag and drop files here or click to browse</p>
</div>
<div id="thumbnail-container" class="thumbnail-container"></div>`
Script
`const dropZone = document.getElementById('drop-zone');
const fileInput = document.getElementById('file-input');
const thumbnailContainer = document.getElementById('thumbnail-container');
dropZone.addEventListener('dragover', (e) => {
e.preventDefault();
dropZone.classList.add('dragover');
});
dropZone.addEventListener('dragleave', () => {
dropZone.classList.remove('dragover');
});
dropZone.addEventListener('drop', (e) => {
e.preventDefault();
dropZone.classList.remove('dragover');
const files = e.dataTransfer.files;
fileInput.files = files; // Set the dropped files to the file input
handleFiles(files);
});
fileInput.addEventListener('change', (e) => {
const files = e.target.files;
handleFiles(files);
});
function handleFiles(files) {
const thumbnails = []; // Array to store generated thumbnails
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = () => {
const thumbnail = createThumbnail(reader.result);
thumbnails.push(thumbnail); // Add thumbnail to the array
if (thumbnails.length === files.length) {
// Append all thumbnails to the thumbnailContainer
thumbnails.forEach((thumb) => {
thumbnailContainer.appendChild(thumb);
});
}
};
reader.readAsDataURL(file);
}
}
}`
Laravel code for uploading multiple images
foreach ($request->file('img') as $image) {
$extension = $image->getClientOriginalExtension();
$filename = Str::slug($lastInsertId) . '-' . Str::random(8) . '.' . $extension;
$folderPath = 'property_images/' . $lastInsertId . '/';
if (!Storage::exists($folderPath)) {
Storage::makeDirectory($folderPath, 0755, true);
}
$resizedImage = Image::make($image)->fit(800, 600)->encode();
Storage::put($folderPath . $filename, $resizedImage->encoded);
}
Image uploading fine when select images all at one time. when selecting one by one , only last image is uploading.
I have explained my issue and code. When multiple image upload only last one is uploaded. so need to check the drag and drop script.
Please or to participate in this conversation.