Drag-and-Drop File Upload
Create a file drop zone that accepts dragged files and shows a preview before uploading via AJAX.
Create a file drop zone that accepts dragged files and shows a preview before uploading via AJAX.
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 });
});
});
Set processData: false and contentType: false in $.ajax for FormData uploads — jQuery must not process the data.