Input Ajax
2024年10月17日
一、认识
二、实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>koa-body</title>
</head>
<body>
<input id="file" type="file" multiple />
<script>
const file = document.getElementById("file");
file.addEventListener("change", uploadSingle);
function uploadSingle(e) {
const {
target: { files },
} = e;
for (const file of files) {
console.log(file);
const ajax = new XMLHttpRequest();
ajax.open("post", "http://localhost:4000/upload", true);
ajax.onreadystatechange = () => {
if (ajax.readyState === 4 && [200, 304].includes(ajax.status)) {
const { response } = ajax;
console.log(response);
}
};
const formData = new FormData();
formData.append("file", file);
formData.append("operator", "柏拉图");
formData.append("filename", file.name);
ajax.send(formData);
}
}
function uploadMultipart(e) {
const {
target: { files },
} = e;
const formData = new FormData();
for (const file of files) {
formData.append("file", file);
}
formData.append("operator", "柏拉图");
const ajax = new XMLHttpRequest();
ajax.open("post", "http://localhost:4000/upload", true);
ajax.onreadystatechange = () => {
if (ajax.readyState === 4 && [200, 304].includes(ajax.status)) {
const { response } = ajax;
console.log(response);
}
};
ajax.send(formData);
}
</script>
</body>
</html>