I'd like to show users the progress of their uploads without using third party plugins, and I know PHP 5.4 has the ability to report upload progress through the session. Unfortunately, Laravel 4.2 doesn't use native PHP sessions, so how could I get this to work?
I've tried placing session_start() at the top of the controller methods of all the related pages (the upload form page, the post page, and the upload progress page). The upload progress function I use just returns the session as a json object, but what I get when I ajax it is an empty object. Here's some code:
In the controller:
public function test(){
session_start();
return View::make('admin.test');
}
public function postTest(){
session_start();
}
public function getTestProgress(){
session_start();
$key = ini_get("session.upload_progress.prefix") . "fileupload";
return Response::json($_SESSION);
}
My test view:
@extends('layouts.master')
@section('head')
<style type="text/css">
#barBlank {
border: solid 1px #fff;
height: 20px;
width: 300px;
}
#barColor {
background-color: yellow;
height: 20px;
width: 0px;
}
#barBlank, #hiddenUploadIframe {
display: none;
}
</style>
@stop
@section('header')
@stop
@section('content')
<div id="barBlank">
<div id="barColor"></div>
</div>
<div id="status"></div>
{{ Form::open( ['action' => 'MyController@postTest', 'id' => 'fileUpload', 'files' => true, 'target'=>'hiddenUploadIframe'] ) }}
<input type="hidden" value="fileupload" name="{{ ini_get('session.upload_progress.name') }}">
<input type="file" name="userfile"><br>
<input type="submit" value="Start Upload">
{{ Form::close() }}
<iframe id="hiddenUploadIframe" name="hiddenUploadIframe" src="about:blank"></iframe>
@stop
@section('footer')
@stop
@section('footerjs')
<script type="text/javascript">
function sendRequest(){
$.get("{{ action('MyController@getTestProgress') }}", function(data){
console.log(data);
var progress = data.upload_progress_fileupload;
var percent = Math.round((progress.bytes_processed / progress.content_length)*100);
$('#barColor').width(percent+'%');
$('#status').html(percent+'%');
if( percent < 100 ){
setTimeout(sendRequest(), 100);
}
else{
$('#barBlank').hide();
$('#status').html('Done.');
}
});
}
$('#fileUpload').submit(function(){
$('#barBlank').css('display', 'block');
setTimeout(sendRequest(), 100);
})
</script>
@stop