I'm trying to come up with a way to display a progress bar for file uploads to my site. So far I came up with the following:
HTML:
<form action="upload/files.php" method="post" enctype="multipart/form-data" id="frmUpload">
<input type="file" name="upfile" id="idUpload">
<input type="text" name="txtV1">
<input type="text" name="txtV2">
<input type="submit" value="Add File" name="btnAddFile" id="btnAddNew" onClick="return btnAddClkd();">
</form>
<div>Current Progress: <span id="idPerc"></span></div>
JavaScript:
function btnAddClkd()
{
var frm_obj = document.getElementById("frmUpload");
if(frm_obj != undefined)
{
var ajaxOK = false;
if(frm_obj.action)
{
try
{
var objFrm = document.forms['frmUpload'];
if(objFrm != undefined)
{
var fd = new FormData(objFrm);
var xhr = new XMLHttpRequest();
if(xhr != undefined)
{
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", frm_obj.action);
xhr.send(fd);
ajaxOK = true;
}
}
}
catch(e)
{
ajaxOK = false;
}
}
if(!ajaxOK)
{
//Failed to send with ajax, use regular method
frm_obj.submit();
}
return false;
}
return true;
}
function uploadProgress(evt)
{
var objPerc = document.getElementById('idPerc');
if(objPerc != undefined)
{
if(evt.lengthComputable)
{
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
objPerc.innerHTML = percentComplete.toString() + '%';
}
else
{
objPerc.innerHTML = "-";
}
}
}
function uploadComplete(evt)
{
var objPerc = document.getElementById('idPerc');
if(objPerc != undefined)
{
objPerc.innerHTML = "Done";
}
}
function uploadFailed(evt)
{
var objPerc = document.getElementById('idPerc');
if(objPerc != undefined)
{
objPerc.innerHTML = "Failed";
}
}
function uploadCanceled(evt)
{
var objPerc = document.getElementById('idPerc');
if(objPerc != undefined)
{
objPerc.innerHTML = "Canceled";
}
}
This concept works for the progress bar while a large file is uploading, but when the upload is done, the web server (or upload/files.php
page) returns the result as a generated HTML page. So my question is how to get that HTML to be displayed? (Currently my upload finishes and my message shows, "Current Progress: Done"
and that's it.)
If you want to replace the entire body of the page with the new content, then you could do:
Add this onreadystatechange handler before you send the request.
xhr.onreadystatechange = function() {
// request finished and response is ready
if (xhr.readyState == 4)
document.body.innerhtml(xhr.responseText);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.