使用formdata
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<p>
<input type="text" name="a" />
</p>
<p>
<input type="file" name="img" accept="image/*" multiple />
</p>
<p>
<button>提交</button>
</p>
<img src="" alt="" />
<script>
function upload() {
const inpA = document.querySelector("[name=a]");
const inpFile = document.querySelector("[name=img]");
const img = document.querySelector("img");
const formData = new FormData(); //帮助你构建form-data格式的消息体
formData.append("a", inpA.value);
for (const file of inpFile.files) {
formData.append("img", file, file.name);
}
fetch("/api/upload", {
body: formData,
method: "POST",
})
.then((resp) => resp.json())
.then((resp) => {
console.log(resp);
if (resp.code) {
//有错误
alert(resp.msg);
} else {
img.src = resp.data;
}
});
}
document.querySelector("button").onclick = upload;
</script>
</body>
</html>
博客内容提及使用FormData,FormData是前端开发中用于处理表单数据的对象,可方便地将表单数据序列化并发送,在Web开发的数据交互场景中较为常用。
1万+

被折叠的 条评论
为什么被折叠?



