我想檢查上傳的文件的進度。我使用的是具有Session類的Kohana框架,但對於上傳進度,我使用的是原生PHP會話。我在Kohana的bootstrap.php中調用session_start()
,這意味着每個頁面請求都會調用session_start()
。延遲填充session.upload_progress數據
上傳表單提交後,我等了1秒鐘,然後開始調用PHP文件來檢查上傳進度,使用jQuery $.ajax()
。
問題是$_SESSION[$key]
($ key包含上傳數據的關鍵字)沒有在首次調用PHP時設置。我已經嘗試過調試了這一點,並且session_id()
返回了正確的會話ID,所以會話肯定是正確的,並且處於活動狀態。在檢查上傳進度之前,我還等了1秒,所以這不是時間問題。即使未設置$_SESSION[$key]
,我仍可以通過繼續解決此問題,但檢查上傳是否完成的方法是當$_SESSION[$key]
未設置。
HTML表單是用jQuery實時創建的,因爲這是一個多文件上傳。下面是一個生成的表單中HTML:
<form action="ajax/upload" id="form-HZbAcYFuj3" name="form-HZbAcYFuj3" method="post" enctype="multipart/form-data" target="frame-HZbAcYFuj3">
<iframe id="frame-HZbAcYFuj3" name="frame-HZbAcYFuj3"></iframe>
<input type="hidden" name="PHP_SESSION_UPLOAD_PROGRESS" value="HZbAcYFuj3">
<input type="file" id="file-HZbAcYFuj3" name="photo" accept="image/jpeg,image/pjpeg,image/png,image/gif">
<button type="button">+ Select Photo</button>
</form>
下面是JavaScript的調用來檢查其進度的PHP:
public function action_uploadprogress()
{
$id = isset($_POST['id']) ? $_POST['id'] : false;
if (!$id)
throw new Kohana_HTTP_Exception_404();
$progress = 0;
$upload_progress = false;
$key = ini_get("session.upload_progress.prefix") . $id;
if (isset($_SESSION[$key]))
$upload_progress = $_SESSION[$key];
else
exit('100');
$processed = $upload_progress['bytes_processed'];
$size = $upload_progress['content_length'];
if ($processed <= 0 || $size <= 0)
throw new Kohana_HTTP_Exception_404();
else
$progress = round(($processed/$size) * 100, 2);
echo $progress;
}
這裏是jQuery的ajax()
要求:
this.send_request = function()
{
$.ajax(
{
url: 'ajax/uploadprogress',
type: 'post',
dataType: 'html',
data: { id: _this.id },
success:
function(data, textStatus, jqXHR)
{
if (textStatus == "success")
{
if (data < 100)
setTimeout(_this.send_request, 1000);
}
}
}
);
};
你在哪裏設置send_request.id? –
爲什麼echo而不是$ this-> response-> body($ progress)? – Darsstar