JSFiddle - React, Tailwind, and code Playground

by Haze32

HTML

<input type="file" id="image-input" multiple accept="image/*" onchange="handleFiles(this)">
<div id="image-previews"></div>
<form id="upload-form">
  <input type="hidden" id="hidden-input" name="updated_images">
  <button type="submit">Submit</button>
</form>

JavaScript

let fileArray = [];

function handleFiles(input) {
  const files = input.files;
  const previewsContainer = document.getElementById('image-previews');
  previewsContainer.innerHTML = '';

  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    fileArray.push(file);

    const img = document.createElement('img');
    img.src = URL.createObjectURL(file);
    img.width = 100;

    const removeBtn = document.createElement('button');
    removeBtn.textContent = 'Remove';
    removeBtn.onclick = () => removeImage(i);

    const preview = document.createElement('div');
    preview.appendChild(img);
    preview.appendChild(removeBtn);

    previewsContainer.appendChild(preview);
  }
}

function removeImage(index) {
  fileArray.splice(index, 1);
  updatePreviews();
}

function updatePreviews() {
  const input = document.getElementById('image-input');
  input.value = null;
  handleFiles({
    files: fileArray
  });
}

document.getElementById('upload-form').addEventListener('submit', (e) => {
  e.preventDefault();

  const hiddenInput = document.getElementById('hidden-input');
  const formData = new FormData();
  fileArray.forEach((file, index) => {
    formData.append(`image_${index}`, file);
  });

  hiddenInput.value = JSON.stringify(fileArray);
});