SnippetUI

Dropzone Upload File

Khu vực tải lên tập tin hiện đại với hỗ trợ kéo và thả.

Tailwind CSSJavaScript

Vùng thả kéo và thả cho phép người dùng tải tệp lên một cách trực quan.

Xem trước

Click to upload or drag and drop

SVG, PNG, JPG or GIF (MAX. 800x400px)

Mã triển khai (Implementation)

<div class="w-full max-w-md mx-auto">
<div id="dropzone" class="border-2 border-dashed border-gray-300 dark:border-zinc-700 rounded-2xl p-10 text-center hover:bg-gray-50 dark:hover:bg-zinc-800/50 transition-colors cursor-pointer flex flex-col items-center justify-center">
  <svg class="w-12 h-12 text-indigo-500 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"></path></svg>
  <p class="text-sm text-gray-600 dark:text-gray-300 font-medium">Click to upload or drag and drop</p>
  <p class="text-xs text-gray-400 mt-2">SVG, PNG, JPG or GIF (MAX. 800x400px)</p>
  <input type="file" id="file-upload" class="hidden" multiple />
</div>
<div id="file-list" class="mt-4 space-y-2"></div>
</div>
<script>
const dropzone = document.getElementById('dropzone');
const input = document.getElementById('file-upload');
const list = document.getElementById('file-list');

dropzone.addEventListener('click', () => input.click());

dropzone.addEventListener('dragover', (e) => {
  e.preventDefault();
  dropzone.classList.add('border-indigo-500', 'bg-indigo-50', 'dark:bg-indigo-900/20');
});

['dragleave', 'dragend'].forEach(type => {
  dropzone.addEventListener(type, () => {
    dropzone.classList.remove('border-indigo-500', 'bg-indigo-50', 'dark:bg-indigo-900/20');
  });
});

dropzone.addEventListener('drop', (e) => {
  e.preventDefault();
  dropzone.classList.remove('border-indigo-500', 'bg-indigo-50', 'dark:bg-indigo-900/20');
  if (e.dataTransfer.files.length) {
    input.files = e.dataTransfer.files;
    updateList();
  }
});

input.addEventListener('change', updateList);

function updateList() {
  list.innerHTML = '';
  Array.from(input.files).forEach(file => {
    const div = document.createElement('div');
    div.className = 'flex items-center justify-between p-3 bg-white dark:bg-zinc-800 rounded-lg shadow-sm border border-gray-100 dark:border-zinc-700';
    div.innerHTML = `<span class="text-sm font-medium text-gray-700 dark:text-gray-200">${file.name}</span><span class="text-xs text-gray-500">${(file.size/1024).toFixed(1)} KB</span>`;
    list.appendChild(div);
  });
}
</script>