首页>>表单>>一个简单的ajax上传 上传进度显示(2013-10-30)

一个简单的ajax上传 上传进度显示

 本例用了jquery.form.js请到演示页面查看

一个简单的ajax上传 上传进度显示
赞赏支持
立刻微信赞赏支持 关闭

 

CSS Code
  1. <style>  
  2. form { displayblockmargin20px autobackground#eeeborder-radius: 10pxpadding15px }  
  3. #progress { position:relativewidth:400pxborder1px solid #dddpadding1pxborder-radius: 3px; }  
  4. #bar { background-color#B4F5B4width:0%; height:20pxborder-radius: 3px; }  
  5. #percent { position:absolutedisplay:inline-blocktop:3pxleft:48%; }  
  6. </style>  

 

XML/HTML Code
  1. <form id="myForm" action="upload.php" method="post" enctype="multipart/form-data">  
  2.      <input type="file" size="60" name="myfile">  
  3.      <input type="submit" value="Ajax File Upload">  
  4. </form>  
  5.    
  6.    
  7.  <div id="progress">  
  8.         <div id="bar"></div>  
  9.         <div id="percent">0%</div >  
  10. </div>  
  11. <div id="message"></div>

 

JavaScript Code
  1. <script>  
  2. $(document).ready(function()  
  3. {  
  4.   
  5.     var options = {   
  6.     beforeSend: function()   
  7.     {  
  8.         $("#progress").show();  
  9.         //clear everything  
  10.         $("#bar").width('0%');  
  11.         $("#message").html("");  
  12.         $("#percent").html("0%");  
  13.     },  
  14.     uploadProgress: function(event, position, total, percentComplete)   
  15.     {  
  16.         $("#bar").width(percentComplete+'%');  
  17.         $("#percent").html(percentComplete+'%');  
  18.   
  19.       
  20.     },  
  21.     success: function()   
  22.     {  
  23.         $("#bar").width('100%');  
  24.         $("#percent").html('100%');  
  25.   
  26.     },  
  27.     complete: function(response)   
  28.     {  
  29.         $("#message").html("<font color='green'>"+response.responseText+"</font>");  
  30.     },  
  31.     error: function()  
  32.     {  
  33.         $("#message").html("<font color='red'> ERROR: unable to upload files</font>");  
  34.   
  35.     }  
  36.        
  37. };   
  38.   
  39.      $("#myForm").ajaxForm(options);  
  40.   
  41. });  
  42.   
  43. </script>  

 upload.php

 

PHP Code
  1. <?php  
  2. $output_dir = "../upload/";  
  3.   
  4.   
  5. if(isset($_FILES["myfile"]))  
  6. {  
  7.     //Filter the file types , if you want.  
  8.     if ($_FILES["myfile"]["error"] > 0)  
  9.     {  
  10.       echo "Error: " . $_FILES["file"]["error"] . "<br>";  
  11.     }  
  12.     else  
  13.     {  
  14.         //move the uploaded file to uploads folder;  
  15.         move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir$_FILES["myfile"]["name"]);  
  16.       
  17.      echo "Uploaded File :".$_FILES["myfile"]["name"];  
  18.     }  
  19.   
  20. }  
  21. ?>  

 


原文地址:http://www.freejs.net/article_biaodan_92.html