PHP Ajax Upload Progress Bar

PHP Ajax Upload Progress Bar

Introduction

The PHP Doc is very detailed it says

The upload progress will be available in the $_SESSION superglobal when an upload is in progress, and when POSTing a variable of the same name as the session.upload_progress.name INI setting is set to. When PHP detects such POST requests, it will populate an array in the $_SESSION, where the index is a concatenated value of the session.upload_progress.prefix and session.upload_progress.name INI options. The key is typically retrieved by reading these INI settings, i.e.

All the information you require is all ready in the PHP session naming

  • start_time
  • content_length
  • bytes_processed
  • File Information ( Supports Multiple )

All you need is to extract this information and display it in your HTML form.

Basic Example

a.html

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
var intval = null;
var percentage = 0 ;
function startMonitor() {
$.getJSON('b.php',
function (data) {
if (data) {
percentage = Math.round((data.bytes_processed / data.content_length) * 100);
$("#progressbar").progressbar({value: percentage});
$('#progress-txt').html('Uploading ' + percentage + '%');

}
if(!data || percentage == 100){
$('#progress-txt').html('Complete');
stopInterval();
}
});
}

function startInterval() {
if (intval == null) {
intval = window.setInterval(function () {startMonitor()}, 200)
} else {
stopInterval()
}
}

function stopInterval() {
if (intval != null) {
window.clearInterval(intval)
intval = null;
$("#progressbar").hide();
$('#progress-txt').html('Complete');
}
}

startInterval();
</script>

b.php

session_start();
header('Content-type: application/json');
echo json_encode($_SESSION["upload_progress_upload"]);

Example with PHP Session Upload Progress

Here is a better optimized version from PHP Session Upload Progress

JavaScript

$('#fileupload').bind('fileuploadsend', function (e, data) {
// This feature is only useful for browsers which rely on the iframe transport:
if (data.dataType.substr(0, 6) === 'iframe') {
// Set PHP's session.upload_progress.name value:
var progressObj = {
name: 'PHP_SESSION_UPLOAD_PROGRESS',
value: (new Date()).getTime() // pseudo unique ID
};
data.formData.push(progressObj);
// Start the progress polling:
data.context.data('interval', setInterval(function () {
$.get('progress.php', $.param([progressObj]), function (result) {
// Trigger a fileupload progress event,
// using the result as progress data:
e = document.createEvent('Event');
e.initEvent('progress', false, true);
$.extend(e, result);
$('#fileupload').data('fileupload')._onProgress(e, data);
}, 'json');
}, 1000)); // poll every second
}
}).bind('fileuploadalways', function (e, data) {
clearInterval(data.context.data('interval'));
});

progress.php



$s = $_SESSION['upload_progress_'.intval($_GET['PHP_SESSION_UPLOAD_PROGRESS'])];
$progress = array(
'lengthComputable' => true,
'loaded' => $s['bytes_processed'],
'total' => $s['content_length']
);
echo json_encode($progress);

Other Examples

  • Tracking Upload Progress with PHP and JavaScript
  • PHP-5.4-Upload-Progress-Example

Progress Bar for file uploads to PHP using AJAX and Bootstrap

removing

async : false;

solved it. But I need to see how to reset the bar now.

add progress bar to jquery ajax file upload

The PHP code for processing the upload does not run until the entire file is uploaded, so it is not possible for you detect how much of the file has been uploaded in that script.

Generally you find upload progress bars built into a browser or some "client-side" program like a Flash application that can control that level of transfer.

For a strict PHP and Javascript implementation there are some workarounds that are fragile and a lot of work and are not very common (hence why you are asking here). There are some jQuery plugins that exist that can do this http://plugins.jquery.com/uploadfile/.

Ajax file upload using core JavaScript with progress bar and additional fields

We can make a ajax request using core JavaScript with XHR for uploading the files.
Create below files:

/* ** upload.js ** */var submit = document.getElementById('submit'), file = document.getElementById('file'), title = document.getElementById('title');progress = document.getElementById('progress');
var upload = function(){
if(file.files.length === 0){ return; }
var data = new FormData(); data.append('title', title.value); data.append('SelectedFile', file.files[0]);
var request = new XMLHttpRequest(); request.onreadystatechange = function(){ if(request.readyState == 4){ try { var resp = JSON.parse(request.response); } catch (e){ var resp = { status: 'error', data: 'Unknown error occurred: [' + request.responseText + ']' }; } console.log(resp.status + ': ' + resp.data); } };
request.upload.addEventListener('progress', function(e){ var progress_width = Math.ceil(e.loaded/e.total * 100) + '%'; progress.style.width = progress_width; }, false);
request.open('POST', 'save.php'); request.send(data);}
submit.addEventListener('click', upload);
/* ** style.css ** */.container {    width: 500px;    margin: 0 auto;}.progress_outer {    border: 1px solid #000;}.progress {    width: 0%;    background: #DEDEDE;    height: 20px;  }
<!-- ** index.html ** --><!doctype html><html><head>    <meta charset="utf-8">    <title>JS File Upload with Progress</title>    <link rel="stylesheet" href="style.css"></head><body>    <div class='container'>        <p>            Enter Title: <input type='text' id='title'>        </p>        <br/>        <p>            Select File: <input type='file' id='file'>        </p>        <br/>        <input type='button' id='submit' value='Upload File'>        <div class='progress_outer'>            <div id='progress' class='progress'></div>        </div>    </div>    <script src='upload.js'></script></body></html>


Related Topics



Leave a reply



Submit