我认为 jQuery 没有内置支持通过 ajax 发布文件。 fetch 确实如此(并且内置于现代浏览器中),因为 body 可以是 Blob 或 BufferSource(ArrayBuffer 或类型化数组)。
您可以将 blob 或缓冲区作为请求的主体发送,或者如果您想在多部分表单上传中将其作为命名参数发送,您可以创建一个 FormData 实例并使用 Blob 作为调用append 时的值。比如:
// 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...*/ 可以是类型化数组、ArrayBuffer 等;详情请见the Blob constructor。
或者,如果这是在 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
}