<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS文件上传</title>
<script type="text/javascript" src="../js/jQuery.js"></script>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#img {
display: block;
width: 9.98rem;
height: 6rem;
border: .01rem solid black;
}
#file {
display: block;
margin: -6rem 0 0 0;
opacity: 0;
width: 10rem;
height: 6rem;
}
#submit {
display: block;
width: 5rem;
height: 2rem;
margin: .5rem 2.5rem;
font-size: .45rem;
text-align: center;
line-height: 2rem;
}
</style>
</head>
<body>
<img id="img" src="" />
<input id="file" type="file" />
<input id="submit" type="button" value="提交文件" />
</body>
</html>
<script type="text/javascript">
// rem布局
$('html').css('font-size', $(window).width() / 10);
// 实例化formData对象
var formData = new FormData();
// 当选取文件时
$('#file').on("change", function() {
var fileList = $("#file")[0].files;
var src = URL.createObjectURL(fileList[0]);
$('#img').attr('src', src);
formData.append("file", fileList[0]);
});
// 点击提交上传时
$("#submit").on('click', function(){
/**
* http 请求对象 XMLHttpRequest
* XMLHttpRequest.open(请求方式, 请求地址, 是否异步 )
* XMLHttpRequest.onload: 请求响应时调用的方法
* e.target.responseText: 服务器响应的文本内容
*/
var httpRequest = new XMLHttpRequest();
httpRequest.open("POST", "http://192.168.0.105/WebTest/FileUploadServlet", true);
httpRequest.onload = function(e){
console.log(e.target.responseText);
}
httpRequest.send(formData);
});
</script>