我想向用户展示他们上传的进度而不使用第三方插件,我知道PHP 5.4能够通过会话报告上传进度。不幸的是,Laravel 4.2不使用本机PHP会话,所以我怎么能让它工作呢?
我尝试将session_start()放在所有相关页面(上传表单页面,帖子页面和上传进度页面)的控制器方法的顶部。我使用的上传进度函数只是将会话作为json对象返回,但是当我ajax时它得到的是一个空对象。这是一些代码:
在控制器中:
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);
}
我的测试视图:
@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