檔案上傳進度upload_progress
阿新 • • 發佈:2018-11-09
前端: <form id="upload-form" action="upload.php" method="POST" enctype="multipart/form-data"> <input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="test" /> <p><input type="file" name="file1" /></p> <p><input class="sub" type="submit" /></p> </form> <div id="progress" class="progress" style="margin-bottom:15px;"> <div class="label">0%</div> </div> <script type="text/javascript"> $('.sub').click(function(){ setTimeout('get_progress()', 100); }) function get_progress(){ $.ajax({ url: "progress.php", //請求的url地址 dataType: "json", //返回格式為json async: true, //請求是否非同步,預設為非同步,這也是ajax重要特性 data: { "<?php echo ini_get("session.upload_progress.name"); ?>": "test" }, //引數值 type: "POST", //請求方式 success: function(req) { $('.label').html(req+"%"); if(req < 100){ setTimeout('get_progress()', 100); //當上傳進度小於100%時,顯示上傳百分比 }else{ $('#progress .label').html('完成!'); //當上傳進度等於100%時,顯示上傳完成 } }, error: function() { alert(0); } }); } </script> 後臺: ----upload.php---- <?php if(is_uploaded_file($_FILES['file1']['tmp_name'])){ move_uploaded_file($_FILES['file1']['tmp_name'], "./{$_FILES['file1']['name']}"); } ?> ----progress.php---- <?php session_start(); $i = ini_get('session.upload_progress.name'); $key = ini_get("session.upload_progress.prefix") . $_POST[$i]; if (!empty($_SESSION[$key])) { //已上傳大小 $current = $_SESSION[$key]["bytes_processed"]; //檔案總大小 $total = $_SESSION[$key]["content_length"]; //向 ajax 返回當前的上傳進度百分比。 echo $current < $total ? ceil($current / $total * 100) : 100; }else{ echo 100; } ?>