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

html5上傳是同步上傳的方式,所以能夠?qū)崿F(xiàn)進(jìn)度條的顯示。
1.上傳文件:
首先我們用ajax來取得<input type="file" id="file_upload">的file對(duì)象:
var file = null;
var input = $("#file_upload");
//文件域選擇文件時(shí), 執(zhí)行readFile函數(shù)
input.addEventListener('change',readFile,false);
function readFile(){
file = this.files[0];
}
然后用FormData()送到后臺(tái)。
var fd = new FormData();
fd.append("file", file);
2.監(jiān)聽事件:給XMLHttpRequest添加上傳中的監(jiān)聽事件,可以得到已上傳的文件大小,用以實(shí)現(xiàn)進(jìn)度條的顯示。
//監(jiān)聽事件
hr.upload.addEventListener("progress", uploadProgress, false);
完整代碼如下:
<html>
<head>
<meta charset="utf-8">
<title>進(jìn)度條測(cè)試</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");
//文件域選擇文件時(shí), 執(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);
//加載進(jìn)度條,同時(shí)顯示信息
$("#percent").html(percentComplete + '%')
$("#progressNumber").css("width",""+percentComplete+"px");
}
}
</script>
</html>
以上就是關(guān)于ajax實(shí)現(xiàn)帶進(jìn)度條的文件上傳全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。
相關(guān)文章
詳解ajax +jtemplate實(shí)現(xiàn)動(dòng)態(tài)分頁
jtemplate是一個(gè)基于JQuery的模板引擎插件,功能非常強(qiáng)大,有了她你就再不用為使用JS綁定數(shù)據(jù)集而發(fā)愁了。本文給大家分享ajax +jtemplate實(shí)現(xiàn)動(dòng)態(tài)分頁,需要的朋友可以參考下本文2015-09-09
ajax智能提示+textbox動(dòng)態(tài)生成下拉框示例代碼
ajax智能提示+textbox動(dòng)態(tài)生成下拉框,下面有個(gè)不錯(cuò)的示例,感興趣的朋友可以參考下,希望對(duì)大家有所幫助2013-12-12
ajax響應(yīng)json字符串和json數(shù)組的實(shí)例(詳解)
下面小編就為大家?guī)硪黄猘jax響應(yīng)json字符串和json數(shù)組的實(shí)例(詳解)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-02-02
Ajax+Asp源代碼]讀取數(shù)據(jù)庫內(nèi)容的表格(沒有用框架)
Ajax+Asp源代碼]讀取數(shù)據(jù)庫內(nèi)容的表格(沒有用框架)...2006-11-11
解決ajax跨域請(qǐng)求數(shù)據(jù)cookie丟失問題
本文主要是從前端jquery和服務(wù)端php為例,分別使用實(shí)例解決ajax跨域請(qǐng)求數(shù)據(jù)cookie丟失問題,推薦給有相同需求的小伙伴們。2015-03-03

