Display file on upload

Categories

JavaScript

Today I found out that we can display an image to preview uploads.

Structur HTML:

<div class="container">
        <div class="dropzone" id="dropzone">
            <p>Drop your files</p>
            <p>or</p>
            <button type="button" class="select-button" id="selectButton">
               Select your files
            </button>
            <input type="file" id="fileInput" hidden multiple accept="image/*">
        </div>
        <div id="previewContainer"></div>
    </div>

Drog And Drog

Here's an example of how we can handle drag and drop natively in javaScript

Delete default behavior

['dragenter', 'dragover', 'dragleave', 'drop'].forEach(event => {
     dropzone.addEventListener(event, preventDefaults);
     document.body.addEventListener(event, preventDefaults);
});

function preventDefaults(e) {
    e.preventDefault();
    e.stopPropagation();
}

Add effect for drag and drop

['dragenter', 'dragover'].forEach(event => {
   dropzone.addEventListener(event, () => {
       dropzone.classList.add('dragover');
    });
});

['dragleave', 'drop'].forEach(event => {
    dropzone.addEventListener(event, () => {
        dropzone.classList.remove('dragover');
     });
});

Manage drop

dropzone.addEventListener('drop', (e) => {
    const files = e.dataTransfer.files;
    handleFiles(files);
});

selectButton.addEventListener('click', () => fileInput.click());
fileInput.addEventListener('change', (e) => handleFiles(e.target.files));

function handleFiles(files) {
   Array.from(files).forEach(createPreview);
}

Preview

To preview the image we need to create a url from the image blob when uploading.


 function createPreview(file) {
    if (!file.type.startsWith('image/')) {
         alert('Veuillez sélectionner uniquement des images.');
         return;
     }

     const previewItem = document.createElement('div');
     previewItem.className = 'preview-item';

     const img = document.createElement('img');
     img.className = 'preview-image';

      // Create image URL
      const objectUrl = URL.createObjectURL(file);
      img.src = objectUrl;
      img.alt = file.name;

       // Free URL after loading
       img.addEventListener('load', () => {
          URL.revokeObjectURL(objectUrl);
        });

        const info = document.createElement('div');
        info.className = 'preview-info';
        info.innerHTML = `
          <p><strong>${file.name}</strong></p>
           <p>Taille: ${(file.size / 1024).toFixed(2)} KB</p>
         `;

        const removeButton = document.createElement('button');
        removeButton.className = 'remove-button';
        removeButton.textContent = 'Supprimer';
        removeButton.onclick = () => previewItem.remove();

        previewItem.appendChild(img);
        previewItem.appendChild(info);
        previewItem.appendChild(removeButton);
        previewContainer.appendChild(previewItem);
}

0 Comments