基于HTML5 Ajax實現(xiàn)文件上傳并顯示進度條
本文實例講解了ajax上傳文件及進度條的實現(xiàn)方法,分享給大家供大家參考,具體內容如下
效果圖:

html5上傳是同步上傳的方式,所以能夠實現(xiàn)進度條的顯示。
1.上傳文件:
首先我們用ajax來取得<input type="file" id="file_upload">的file對象:
var file = null;
var input = $("#file_upload");
//文件域選擇文件時, 執(zhí)行readFile函數(shù)
input.addEventListener('change',readFile,false);
function readFile(){
file = this.files[0];
}
然后用FormData()送到后臺。
var fd = new FormData();
fd.append("file", file);
2.監(jiān)聽事件:給XMLHttpRequest添加上傳中的監(jiān)聽事件,可以得到已上傳的文件大小,用以實現(xiàn)進度條的顯示。
//監(jiān)聽事件
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");
//文件域選擇文件時, 執(zhí)行readFile函數(shù)
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);
//監(jiān)聽事件
xhr.upload.addEventListener("progress", uploadProgress, false);
//發(fā)送文件和表單自定義參數(shù)
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實現(xiàn)帶進度條的文件上傳全部內容,希望對大家的學習有所幫助。
相關文章
ajax接收Date類型的數(shù)據(jù)時會把數(shù)據(jù)轉換為時間戳
ajax接收Date類型的數(shù)據(jù)時將會把數(shù)據(jù)轉換為時間戳,下面是具體的示例,大家可以參考下2014-05-05
asp+ajax實現(xiàn)靜態(tài)頁面分頁的代碼
asp+ajax實現(xiàn)靜態(tài)頁面分頁的代碼...2007-11-11
Ajax商品分類三級聯(lián)動的簡單實現(xiàn)(案例)
下面小編就為大家?guī)硪黄狝jax商品分類三級聯(lián)動的簡單實現(xiàn)(案例)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-08-08

