Tracking Upload progress PHP and JavaScript

Source: Internet
Author: User
One problem that has plagued Web developers for many years is how to add real-time information to their own applications, such as file Upload progress bars. Users don't have patience, they don't want to wait, and the browser is doing anything, wondering if it has been frozen or if they have a slow connection. Provides a progress indicator to provide users with useful information and let them know what happened.

One problem that has plagued Web developers for many years is how to add real-time information to their own applications, such as file Upload progress bars. Users don't have patience, they don't want to wait, and the browser is doing anything, wondering if it has been frozen or if they have a slow connection. Provides a progress indicator to provide users with useful information and let them know what happened.

In the first thought, you may think that this can be done easily by obtaining the file size from the user's computer first, then, some simple calculations are performed to upload the files in the directory to the server. With regard to the second idea, you will find that things are not as simple as you think.

JavaScript can access the name, type, or even width of a file and the height of the local image, but it is not until HTML5, and it can access the size of a file. Unfortunately, HTML5 is still an unfinished standard, not supported by all browsers. Another solution is to rely on a Flash, Java or install ActiveX plug-in. no, thanks, I will pass. Another solution is to install the optional PHP Cache extension, which may not be available in your hosting environment. This seems a little tricky, such a small task.

This seems like all the options are full of troubles and tasks have quickly become a headache. But in Yuda's words, "No... there is another one ."

Many of the reasons I like PHP are that it makes seemingly difficult tasks easy. In PHP 5.4, they have used a new set of configuration options to implement session. upload_progress.

In this article, I will show you how this feature can be used to create a simple Upload progress bar without any external library or browser dependencies. I will first discuss how it works, and then I will guide you through the tasks that have been created (an upload form, some JavaScript, a little bit of CSS and a file returns the loaded status) the four required files.

Meeting Upload progress

In addition to the general requirements, there are two more to allow file upload to track the progress. This session. upload_progress.enabled command must be enabled, and there must be a Web form in the hidden field and the specified name session. upload_progress.name command. When session. upload_progress.enabled is true (because it is in PHP 5.4 by default and later) and $ _ POST [session. in upload_progress.name], information transmission is an available $ _ SESSION ultra-global array.

The $ _ SESSION array output by print_r () looks similar to the following file transfer process:

Arrangement ([upload_progress_myForm] => array ([START_TIME] => 1323733740 [CONTENT_LENGTH] => 721127769 [bytes_processed] => 263178326 [completed] => [file] => array ([ 0] => array ([FIELD_NAME] => USERFILE [name] => ubuntu-10.04.3-desktop i386.iso [tmp_name value] => [error] => 0 [done] => [START_TIME] => 1323733740 [bytes_processed] => 263178026 ))))

When you develop local or fast networks and upload small files, you will not be able to visually observe the progress because the transfer happens so quickly. In this case, you may want to try to transfer large files. Make sure that the php. ini file is set to allow large uploads, especially the post_max_size and upload_max_filesize commands, and then confirm that they are rational values.

Create a form

The first file I will introduce is the upload form. To make things as simple as possible, this example will be posted to the time when only one file can be uploaded. In addition, I will not disturb after saving the file that has been uploaded.

The following code is form. php:

1234567891011121314151617181920212223242526 <? If ($ _ SERVER ["REQUEST_METHOD"] = "POST "&&! Null ($ _ FILES ["userfile"]) {// move_uploaded_file () to}?> File upload progress bar </TITLE> <链接相对= “样式表” 类型="“文/" css” href="“style.css文件”">   <分区编号= “bar_blank”> <分区编号= “bar_color”> <分区编号= “状态”> <形式的行动= “ "Method =" POST "ID =" myForm "is enctype =" multi-part/form data "target =" hidden_iframe "> <输入类型= “隐藏” 值="“myForm的”    名称=" “<?php的回声ini_get(” session.upload_progress.name ?“);> "> <输入类型= “文件” 名称="“USERFILE”">
<输入类型= “提交” 值="“开始上传”"> <脚本类型= “文 javascript的” src="“的script.js”">  

The code in this example has been omitted to actually process the file, making it easy. If you are interested in what such code should look like, please check the article file upload using PHP by Timothy Boronczyk.

Header, which provides the webpage title and includes the style sheet, you will find a small set of div elements. The DIV with the ID "bar_blank" is the progress bar of the container. The ID is "bar_color". In div, the upload progress of the file is dynamically updated. The "status" div displays the uploaded percentage value.

This form is set to submit to the same URL and direct its target attribute to a hidden iframe element. Submitting a form to a hidden framework allows you to keep the visitor on the same page while the work is being done in the background. In fact, this is a common practice for "Ajax file upload", because it is impossible to directly send the content of a file using JavaScript XmlHttpRequest object.

In the table, a special hidden field needs to be filled with the $ _ SESSION array, and a file Upload input and submit button appears. Submitting a form triggers a JavaScript function startUpload () that will be defined in the included JavaScript file.

At the bottom of the page is a hidden framework, which will publish and import the script. js file.

Add some styles

The next File, style.css, is quite straightforward. I define the container size of the progress bar and give it a black border of 1px, the color of the progress bar because of its loading, whether it is IFRAME and the progress bar is hidden.

123456789101112131415 # Bar_blank {boundary: #000 of solid 1px; height: 20 pixels; width: 300 pixels; }# bar_color {background color: #006666; height: 20 pixels; width: 0PX ;} # bar_blank, # hidden_iframe {display: none ;}
Client functions

The script. js file is the largest group file. It contains six functions, which I will discuss below. Many people like to use jQuery to provide some functions here. of course you can do this. if you like it, I personally prefer the old school practice. Similar to how Japanese people put products in hand-made products with high value, I just feel more keen on code, if it is my own.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 Function toggleBarVisibility () {document. getElementById ("bar_blank") of variant E =; e. style. display = (e. style. display = "block "?) "None": "block";} function createRequestObject () {variant http; if (navigator. appName = "Microsoft Internet Explorer") {HTTP = new ActiveXObject ("Microsoft. XMLHTTP ") ;}otherwise {HTTP = http returned by the new XMLHttpRequest ();} function sendRequest () {variant http = createRequestObject (); http. open ("GET", "progress. php "); http. onreadystatechange = function () {use handleResponse (HTTP) ;}; http. send (null);} function with handleResponse (HTTP) {reactive response; if (http. readySta Te = 4) {response = document. getElementById ("bar_color") of http. responseText ".) If 0 is in total, the response is + "%"; the document. getElementById ("status ".) InnerHTML = response + "%"; if (response <100) {setTimeout ("sendRequest will ()", 1000) ;}otherwise {toggleBarVisibility. getElementById ("status ".) InnerHTML = "Done (finished )." ;}}} SetTimeout ("sendRequest will ()", 1000) of startUpload () {toggleBarVisibility ();} (function () {document. onsubmit = startUpload;}) of getElementById ("myForm ;})();

The "bar_blank" div on the toggleBarVisibility () function shows or hides the progress bar to set the appropriate style as needed. Initially, it is hidden at the beginning, but will appear at the beginning of an upload, and then hidden again when the upload is complete.

The createRequestObject () function creates an XMLHttpRequest or ActiveXObject based on the user's browser object. This feature may be provided by jQuery or some other JavaScript frameworks that most people expect.

The sendRequest () function requests the progress. php file and a GET request, and then calls the handleResponse () function to process the returned data.

The handleResponse () function handles the progress from the response progress. php, which will depend on the file upload progress between 1. I also updated the appropriate div value of "status. If the percentage of current is less than 100 and then the native setTimeout () function of JavaScript is called to update another request one second later (you may need to adjust this value if applicable ), otherwise, I hide the progress bar and status settings as "finished" again ".

The startUpload () function makes the load column visible and sends an update request with a delay of 1 second. This small latency is necessary to enable the upload time.

The last function is an self-executed anonymous function that registers startUpload () and form submission events.

Real-time progress

The last file that brings everything together is the progress. php file:

123456789101112 <? PHP in session_start (); the key of dollar = ini_get ("session. upload_progress.prefix "). "MyForm"; if (! Null ($ _ SESSION [$ Key]) {$ current =$ _ SESSION [$ Key] ["bytes_processed"]; total $ =$ _ SESSION [$ Key] ["CONTENT_LENGTH"]; Echo $ current <$ total? CEIL ($ current/$ total amount * 100): 100;} otherwise {echo 100 ;}

The number of bytes transmitted on the script execution is currently in the Total file size, multiplied by 100, and rounded to a percentage into some simple mathematics.

The key to transmission information is a set of concatenation with the value of the session. upload_progress.prefix command and hiding the value of the session. upload_progress.name field. Because my form passed the "myForm meeting", the focus of the meeting is to confirm the ini_get ("session. upload_progress.prefix "). "myForm" ini_get ("session. upload_progress.prefix "). "myForm ".

The following is the progress bar of the action:

Fine-tuning behavior

PHP provides some additional commands to help you fine-tune the session Upload behavior, you should know. For example, session. upload_progress.cleanup is set to 1 by default. after cleaning, upload the additional session data that has been completed. You must be careful to avoid potential competition conditions.

Let's look at the code progress. php. you will find that I checked to see if $ _ SESSION [$ key] is null or not, and then continue. My JavaScript function fires every second, as long as the result is less than 100 from the returned progress. php. If session. upload_progress.cleanup is enabled, $ _ SESSION [$ key] will not exist for the next check after my script obtains 99% Upload and 1/2-second upload. If I don't take this into consideration, then my JavaScript function may keep shooting, as well after the upload is complete.

The other two commands are session. upload_progress.freq and session. upload_progress.min_freq, which determine how long the meeting should be updated. The value of frequency can be given in any byte (100) or percentage of the total number of bytes (2%. Min_freq is measured in seconds and represents the minimum number of seconds between updates. Apparently, if min_freq is set to update every 1 second, this would be meaningless JavaScript to check every 100 milliseconds.

Summary

Now you should have a file Upload progress bar with a strong grasp of how to create a session Upload progress function. Looking forward to the future, I encourage you to try uploading multiple files and give the option $ _ SESSION [$ key] ["cancel_upload"] to cancel using the Upload in progress. or any other idea you have. Please share with us what you have done to benefit others, enjoy and comment on your experiences and improvements!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.