AJAX File Upload
Use FormData with jQuery's $.ajax() to upload files asynchronously without a page reload.
Use FormData with jQuery's $.ajax() to upload files asynchronously without a page reload.
$("#uploadForm").on("submit", function(e) {
e.preventDefault();
const fd = new FormData(this);
$.ajax({
url: "/api/upload",
type: "POST",
data: fd,
processData: false, // required for FormData
contentType: false, // required for FormData
success: function(res) {
$("#preview").attr("src", res.url);
},
error: function() {
alert("Upload failed");
}
});
});
Set processData: false and contentType: false when sending FormData — both are required.