I don't think jQuery has built-in support for posting files via ajax. fetch
does though (and is built into modern browsers), because body can be a Blob
or a BufferSource
(ArrayBuffer
or typed array).
You can either send the blob or buffer as the body of the request, or if you want to send it as a named parameter in a multipart form upload, you can create a FormData
instance and use a Blob
as the value when calling append
. Something like:
// This is off the top of my head, not meant to be a perfect,
// all-singing, all-dancing example. You'll need to read the
// linked documentation and adjust as necessary.
var blob = new Blob([/*...file data...*/], {type: "appropriate/mimetype"});
var data = new FormData();
data.append("parameterName", blob);
fetch("php/upload.php", {
method: "POST",
body: data
})
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.text(); // or perhaps response.json()
})
.then(result => {
// ...use the response
})
.catch(error => {
// ...handle/report the error
});
/*...file data...*/
can be a typed array, an ArrayBuffer
, etc.; see the Blob
constructor for details.
Or if this is within an async
function:
try {
let blob = new Blob([/*...file data...*/], {type: "appropriate/mimetype"});
let form = new FormData();
data.append("parameterName", blob);
let response = await fetch("php/upload.php", {
method: "POST",
body: data
});
if (!response.ok) {
throw new Error("HTTP status " + response.status);
}
let result = await response.text(); // or perhaps response.json()
})
// ...use the response
} catch(error) {
// ...handle/report the error
}