<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>利用js的FormData对象快速收集表单信息及无刷新上传头像</title>
<style>
#preview, .img, img {
width: 200px;
height: 200px;
}
#preview {
border: 1px solid #000;
}
</style>
</head>
<body>
<form enctype="multipart/form-data" id="tf" onsubmit="return false">
用户名:<input type="text" name="user"><br/>
密码:<input type="password" name="pass"><br/>
头像:<input type="file" name="file" onchange="preview(this)"><br/>
<div id="preview"></div>
<input type="submit" value="提交" onclick="test()">
</form>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<script type="text/javascript">
function test(){
var form = new FormData(document.getElementById("tf"));
// var req = new XMLHttpRequest();
// req.open("post", "${pageContext.request.contextPath}/public/testupload", false);
// req.send(form);
$.ajax({
url:"upload.php",
type:"post",
data:form,
processData:false,
contentType:false,
success:function(data){
window.clearInterval(timer);
console.log("over..");
},
error:function(e){
alert("错误!!");
window.clearInterval(timer);
}
});
}
function preview(file) {
var prevDiv = document.getElementById('preview');
if (file.files && file.files[0]) {
var reader = new FileReader();
reader.onload = function(evt) {
prevDiv.innerHTML = '<img src="' + evt.target.result + '" />';
}
reader.readAsDataURL(file.files[0]);
} else {
prevDiv.innerHTML = '<div style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\'' + file.value + '\'"></div>';
}
}
</script>
</body>
</html>
upload.php
<?php
var_dump($_FILES);die;//这里直接写自己后台逻辑咯
?>