Created
December 1, 2014 10:06
-
-
Save vittore/c31232122c685333aac8 to your computer and use it in GitHub Desktop.
progress bar
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
---- download action ----- | |
$session = new Session(); | |
$session->set('downloadPercent',0); | |
$filesize = filesize($filePath); | |
$handle = fopen($filePath, 'rb'); | |
header( 'Content-Disposition: attachment; filename="' .$fallbackFilename . '"' ); | |
header( 'Pragma: no-cache' ); | |
$curr_kb=0; | |
while($chunk = fread($handle, 1000)) // chunk size may depend on your filesize | |
{ | |
echo $chunk; | |
flush(); | |
$curr_kb+=1000; | |
$percent = ceil(($curr_kb / $filesize) * 100); | |
$session->set('downloadPercent',$percent); | |
} | |
fclose($handle); | |
---- progress action ---- | |
/** | |
* @Route("/getProgress", name="getDownloadProgress") | |
* @Template() | |
*/ | |
public function getDownloadProgressAction() | |
{ | |
$session = new Session(); | |
$response = new Response(json_encode( $session->get('downloadPercent'))); | |
$response->headers->set('Content-Type', 'application/json'); | |
return $response; | |
} | |
---- ajax & html ----- | |
<div id="downloadBar" class="progress progress-striped" style="display:none; margin-top: 20px;margin-bottom: 20px"> | |
<div id="progress-bar" class="progress-bar progress-bar-info" style="width: 0%"></div> | |
</div> | |
<script> | |
function GetProgress() { | |
$.ajax({ | |
url: "{{ path("getDownloadProgress") }}", | |
success: function (data) { | |
$("#progress-bar").css('width', Math.round(data) + '%') | |
if (Math.round(data) >= 100) { | |
isDone = true; | |
$("#downloadBar").hide(); | |
} else { | |
setTimeout(GetProgress(), 2000); | |
} | |
} | |
}); | |
} | |
$(".downloadHref").click( | |
function() { | |
$("#downloadBar").show(); | |
GetProgress(); | |
} | |
); | |
</script> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment