本文實例講解了ajax上傳文件及進度條的實現方法,分享給大家供大家參考,具體內容如下
效果圖:
html5上傳是同步上傳的方式,所以能夠實現進度條的顯示。
1.上傳文件:
首先我們用ajax來取得<input type="file" id="file_upload">的file對象:
var file = null; var input = $("#file_upload"); //文件域選擇文件時, 執行readFile函數 input.addEventListener('change',readFile,false); function readFile(){ file = this.files[0]; }
然後用FormData()送到後臺。
var fd = new FormData(); fd.append("file", file);
2.監聽事件:給XMLHttpRequest添加上傳中的監聽事件,可以得到已上傳的文件大小,用以實現進度條的顯示。
//監聽事件 hr.upload.addEventListener("progress", uploadProgress, false);
完整代碼如下:
<html>
<head>
<meta charset="utf-8">
<title>進度條測試</title>
<script type="text/javascript" src="../js/jquery-1.11.1.min.js"></script>
</head>
<body>
<input type="file" id="file_upload"/>
<input type="button" value="上傳" id="upload"/>
<div style="background:#848484;width:100px;height:10px;margin-top:5px">
<div id="progressNumber" style="background:#428bca;width:0px;height:10px" >
</div>
</div>
<font id="percent">0%</font>
</body>
<script>
var file = null;
$(function(){
$("#upload").click(function(){
upload();
});
});
var input = document.getElementById("file_upload");
//文件域選擇文件時, 執行readFile函數
input.addEventListener('change',readFile,false);
function readFile(){
file = this.files[0];
}
//上傳文件
function upload(){
var xhr = new XMLHttpRequest();
var fd = new FormData();
fd.append("fileName", file);
//監聽事件
xhr.upload.addEventListener("progress", uploadProgress, false);
//發送文件和表單自定義參數
xhr.open("POST", "../UploadServlet",true);
xhr.send(fd);
}
function uploadProgress(evt){
if (evt.lengthComputable) {
//evt.loaded:文件上傳的大小 evt.total:文件總的大小
var percentComplete = Math.round((evt.loaded) * 100 / evt.total);
//加載進度條,同時顯示信息
$("#percent").html(percentComplete + '%')
$("#progressNumber").css("width",""+percentComplete+"px");
}
}
</script>
</html>
以上就是關於ajax實現帶進度條的文件上傳全部內容,希望對大家的學習有所幫助。
原文鏈接:點擊打開鏈接