Want to add progress bars to a process on your site? We recently created an FTP-based file packager for our Food Service Gateway used to support the Moe's Nutritional Guide. Clients upload images and enter data into the backend, then the generated XML, swf, and included images are uploaded to the client's site. Due to the large number of files, we felt this could benefit from progress bars. Without an "upload in progress" page of some sort, the script would appear to hang until the upload was complete. During this time, a user might be tempted to hit stop or refresh. These bars give the user feedback while the script is working. This just shows the percentage of files that have been uploaded, not the percentage of bytes.
This method utilizes <cfflush> to generate javascript which updates the progress bars.
First, let's look at the HTML for the progress bar:
<cfoutput>
<div id="progressBar" style="background-color: ccc; width: 0;">0%</div>
</cfoutput>
<cfflush>
That's it! This is just a div to hold the percent uploaded text. I've applied a background color so you can see the bar grow as files are uploaded. Be sure to <cfflush> this to the browser before we begin uploading the files.
Next we set variables to describe our file locatations, get the list of files to upload, and open the FTP connection.
<cfset localFolderName = "c:\example\directory">
<cfset remoteFolderName = "/test/">
<cfdirectory action="list" directory="#localFolderName#" name="q_getClientFiles">
<cfftp action = "open" username = "username" password = "password"
server = "servername" port="21" connection = "FTPconn" timeout="30"
retrycount="3" stopOnError = "Yes">
Now it's time to upload the files:
<cfloop query="q_getClientFiles">
<cfftp action="putfile" connection="FTPconn" localfile="#localFolderName#\#q_getClientFiles.name#"
remotefile="#q_getClientFiles.name#">
<cfset ftpProgress="#q_getClientFiles.currentrow/q_getClientFiles.recordCount#">
<cfoutput>
<script type="text/javascript">
document.getElementById('progressBar').innerHTML = '#round(ftpProgress*100)#%';
document.getElementById('progressBar').style.width = '#round(ftpProgress*200)#px';
</script>
</cfoutput>
<CFFLUSH>
</cfloop>
Here we loop over the list of files to upload. First, the file is uploaded to the server. Next, we set a variable to show the updated percentage of files uploaded. Finally, we output a javascript nugget to update the percent completed text and the width in the 'progressbar' div created above. In this example I multiplied the percent completed by 200 so the completed progress bar is 200 pixels wide. 400 would have worked just as well. Finish off the loop iteration with another <cfflush> to send your javascript to the browser.
Go check it out on a directory full of images!
Comments (0)