原理:
使用 FormData对象,将要发送给后台的数据 都 append该对象中,包括文件,最后将这个对象发送给后台。
<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>HTML5 Ajax Uploader</title>
<script src="jquery.js"></script>
</head>
<body>
<p>
<input type="file" id="upfile">
</p>
<p>
<input type="button" id="upJS" value="用原生JS上传">
</p>
<p>
<input type="button" id="upJQuery" value="用jQuery上传">
</p>
<script>
/*原生JS版*/
document.getElementById("upJS").onclick = function () {
/* FormData 是表单数据类 */
var fd = new FormData(); //创建一个表单对象
var ajax = new XMLHttpRequest();
fd.append("upload", 1); //将数据append 到表单对象中
/* 把文件添加到表单里 */
fd.append("upfile", document.getElementById("upfile").files[0]);
ajax.open("post", "/messagefile", true); //提交方式 接口地址 同步异步?
ajax.setRequestHeader("token","11111"); // 设置 请求头
ajax.onload = function () {
console.log("准备完毕");
console.log(ajax.responseText);
console.log(fd);
};
ajax.send(fd); //发送 ajax请求 上传文件
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && ajax.status == 200) {
//步骤五 如果能够进到这个判断 说明 数据 完美的回来了,并且请求的页面是存在的
console.log(ajax.responseText);//输入相应的内容
}
}
}
/* jQuery 版 */
$('#upJQuery').on('click', function () {
var fd = new FormData();
fd.append("upload", 4);
fd.append("upfile", $("#upfile").get(0).files[0]);
fd.append("Headers",000);
$.ajax({
url: "/messagefile",
type: "POST",
processData: false,
contentType: false,
headers:{
token:"555"
},
data: fd,
success: function (d) {
console.log(d);
}
});
});
</script>
</body>
</html>