一、概述
二、使用
<form id="upload" method="post" action="">
<input type="text" name="username" value=""/>
<input type="password" name="paw" value=""/>
<input type="button" value="提交"/>
</form>
//获取一个form表单对象
let form = document.getElementById("form");
//用这个表单对象来初始化FormData对象
let formdata = new FormData(form);
//我们可以通过name来访问表单中的字段
formdata.get("username"); //获取username的值
formdata.get("pwd"); //获取pwd的值
//我们也可以添加数据
formdata.append("token","fegahgag54");
formdata.get("username"); //获取key为username的第一个值
formdata.getAll("username"); //获取key为username的所有值,返回一个数组
formdata.append("k1","v1");
formdata.append("k1","v2");
formdata.append("k2","v2");
formdata.getAll("k1"); //["v1","v2"]
formdata.get("k2"); //"v2"
formdata.append("k1","v1");
formdata.set("k1","v2");
formdata.get("k1"); //"v2"
formdata.append("k1","v1");
formdata.has("k1"); //true
formdata.has("k2"); //false
formdata.append("k1","v1");
formdata.delete("k1");
formdata.get("k1"); //null
formdata.append("k1","v1");
formdata.append("k2","v2");
for(let [key,value] of formdata.entries()){
console.log(key +":"+ value)
}
输出:
"k1:v1"
"k2:v2"
formdata.append("k1","v1");
formdata.append("k2","v2");
for(let value of formdata.values()){
console.log(value)
}
输出:
"v1"
"v2"
<input type="file" id="upload"/>
<input type="button" id="upload-btn" value="上传"/>
let btn = document.getElementById("upload-btn");
btn.onclick = function(){
let file = document.getElementById("upload");
let formdata = new FormData();
formdata.append("file",file.files[0]);
fetch("https://www.baidu.com",{
method:'POST',
body:formdata
}).then(d=>{
console.log("result is" + d);
alert("上传成功");
})
}
三、浏览器兼容性