欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

基于HTML5 Ajax實(shí)現(xiàn)文件上傳并顯示進(jìn)度條

 更新時(shí)間:2016年02月25日 17:12:09   作者:LZGS_4  
這篇文章主要介紹了基于HTML5 Ajax實(shí)現(xiàn)文件上傳并顯示進(jìn)度條的相關(guān)資料,需要的朋友可以參考下

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

效果圖:

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)聽(tīng)事件:給XMLHttpRequest添加上傳中的監(jiān)聽(tīng)事件,可以得到已上傳的文件大小,用以實(shí)現(xiàn)進(jìn)度條的顯示。

 
//監(jiān)聽(tīng)事件 
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)聽(tīng)事件 
 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)文章

最新評(píng)論