Anyone who has developed file upload progress bar with following:
Ajax Javascript HTML C based CGI
I am stuck at one point. I am not able to read each updated progress bar value from CGI script.
/*****************CLIENT SIDE CODE*************************/
var intervalID;
var percentage;
var request;
var tempvar=0;
var progress;
function polling_start() { // This is called when user hits FILEULOAD button
//alert ("polling_start");
intervalID = window.setInterval(send_request,1000);
}
window.onload = function (){
request = initXMLHttpClient();
progress = document.getElementById('progress');
}
function initXMLHttpClient() {
//alert("send_request");
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp
}
function send_request()
{
request.onreadystatechange = request_handler;
request.open("GET","progress_bar.txt",true);
request.send(null);
}
function request_handler()
{
if (request.readyState == 4 && request.status == 200)
{
document.getElementById("progress").innerHTML= request.responseText + '%';
document.getElementById("progress").style.width = request.responseText + '%';
document.getElementById("progress").style.backgroundColor = "green";
}
}
/***********************SERVER SIDE CODE*****************************/
cgiFormFileSize("UPDATEFILE", &size); //UPDATEFILE = file being uploaded
cgiFormFileName("UPDATEFILE", file_name, 1024);
cgiFormFileContentType("UPDATEFILE", mime_type, 1024);
buffer = malloc(sizeof(char) * size);
if (cgiFormFileOpen("UPDATEFILE", &file) != cgiFormSuccess) {
exit(1);
}
output = fopen("/tmp/cgi.tar.gz", "w+");
printf("The size of file is: %d bytes", size);
inc = size/(1024*100);
while (cgiFormFileRead(file, b, sizeof(b), &got_count) == cgiFormSuccess)
{
fwrite(b,sizeof(char),got_count,output);
i++;
if(i == inc && j<=100)
{
fptr = fopen("progress_bar.txt", "w");
fprintf(fptr, "%d" ,j);
fseek(fptr, 0, SEEK_SET);
i = 0;
fflush(fptr);
fclose(fptr);
j++; // j is the progress bar increment value
}
}
fclose(output);
cgiFormFileClose(file);
retval = system("mkdir /tmp/update-tmp;\
cd /tmp/update-tmp;\
tar -xzf ../cgi.tar.gz;\
bash -c /tmp/update-tmp/update.sh");
}
/********************************************************************/
So,Ajax is not able to read each incremented value of "j". Therefore the progress bar starts as soon as the CGI stops writing to the text file. However, Ajax is able to display values from 1 to 100 (If I put sleep(1); the progress bar could be seen incremented at each second) ; but not at appropriate time.