SyntaxStudy
Sign Up
jQuery Intermediate 5 min read

File Drop Zone

Drag-and-Drop File Upload

Create a file drop zone that accepts dragged files and shows a preview before uploading via AJAX.

Example
const $zone = $("#drop-zone");
$zone.on("dragover dragenter", e => { e.preventDefault(); $zone.addClass("dragging"); })
     .on("dragleave drop",     e => { e.preventDefault(); $zone.removeClass("dragging"); });
$zone.on("drop", function(e) {
  const files = e.originalEvent.dataTransfer.files;
  [...files].forEach(file => {
    if (!file.type.startsWith("image/")) { alert("Images only"); return; }
    const reader = new FileReader();
    reader.onload = ev => $("<img>").attr("src", ev.target.result).appendTo("#preview");
    reader.readAsDataURL(file);
    const fd = new FormData(); fd.append("file", file);
    $.ajax({ url: "/api/upload", method: "POST", data: fd, processData: false, contentType: false });
  });
});
Pro Tip

Set processData: false and contentType: false in $.ajax for FormData uploads — jQuery must not process the data.