本文實(shí)例講解了ajax上傳文件及進(jìn)度條的實(shí)現(xiàn)方法,分享給大家供大家參考,具體內(nèi)容如下
效果圖:
![](http://img.jbzj.com/file_images/article/201602/2016225165734644.jpg?2016125165746)
html5上傳是同步上傳的方式,所以能夠?qū)崿F(xiàn)進(jìn)度條的顯示。
1.上傳文件:
首先我們用ajax來(lái)取得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í)有所幫助。
您可能感興趣的文章:- 基于ajax實(shí)現(xiàn)文件上傳并顯示進(jìn)度條
- 基于HTML5 Ajax文件上傳進(jìn)度條如何實(shí)現(xiàn)(jquery版本)
- js HTML5 Ajax實(shí)現(xiàn)文件上傳進(jìn)度條功能
- php ajax實(shí)現(xiàn)文件上傳進(jìn)度條
- HTML5 Ajax文件上傳進(jìn)度條如何顯示
- 基于Ajax技術(shù)實(shí)現(xiàn)文件上傳帶進(jìn)度條