1、XHR2 上传方案
XmlHttpRequest Level2 已经原生态支持,异步文件上传。
2、实现代码。
网页代码实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>XmlHttpRequest Level2文件上传</title>
<style type="text/css">
#uploadBtn,#uploadStopBtn{
width: 100px;
height: 30px;
line-height: 30px;
background: blue;
margin: 20px;
display: block;
border-radius: 5px;
text-align: center;
color: white;
cursor: pointer;
}
</style>
</head>
<body>
<input id="uploadFile" type="file"></input><br/>
<span id="uploadBtn">开始上传</span>
状态:<span id="uploadStatus"></span><br/>
<span id='uploadStopBtn'>停止上传</span>
</body>
<script type="text/javascript">
var uploadBtn = document.getElementById("uploadBtn");
function ajaxUpload(url){
var uploadStatus = document.getElementById("uploadStatus");
var stopBtn = document.getElementById("uploadStopBtn");
var file = document.getElementById("uploadFile").files[0];
//创建XHR对象
var xhr = new XMLHttpRequest();
//ajax上传开始
xhr.onloadstart = function(event){
console.log('开始上传');
uploadStatus.innerHTML='开始上传';
stopBtn.style.display = 'block';
stopBtn.onclick = function(){
this.style.display = 'none';
xhr.abort();
};
}
//ajax上传完成
xhr.onload = function(event){
console.log('上传成功');
uploadStatus.innerHTML='上传成功';
console.log(xhr.responseText);
}
//ajax上传错误
xhr.onerror = function(event){
console.log('发生错误');
uploadStatus.innerHTML='发生错误';
}
//ajax上传取消
xhr.onabort = function(event){
console.log('上传取消');
uploadStatus.innerHTML='上传取消';
}
//ajax传输结束
xhr.onloadend = function(){
console.log('传输结束');
stopBtn.style.display = 'none';
}
//ajax上传进度
//xhr和xhr.upload 都有progress事件
//xhr.progress是下载进度,xhr.upload.progress是上传进度
xhr.upload.onprogress = function(event){
if(event.lengthComputable){
var percent = Math.round(event.loaded * 100 / event.total);
console.log('上传进度:%d%',percent);
uploadStatus.innerHTML=percent;
}
}
//ajax上传表单创建
var formData = new FormData();
formData.append("uploadFile",file);
formData.append("key1","value1");
formData.append("key2","value2");
//ajax发送数据
xhr.open('POST',url,true);
xhr.send(formData);
}
uploadBtn.onclick = function(){
var url= "http://127.0.0.1:6158/ajax/rest/FileUploadService/upload";
ajaxUpload(url);
}
</script>
</html>
JRainFramew