Tracking upload progress PHP and JavaScript

Source: Internet
Author: User
Tags file upload progress bar

A problem that has plagued Web developers for many years is how to add to their applications, such as file upload progress bars and real-time information. Users are impatient; they don't want to wait, while browsers are doing something, wondering if they have been frozen or if they have a slow connection. A progress indicator is provided to provide users with useful information and let them know what happened.
First of all, you may want to make it possible to easily obtain the file size from your computer for the first time, then, execute the file in which the directory is located to perform some simple calculations on the uploaded server. With regard to the second idea, you will find that things are not that simple.
JavaScript can access the file name, type, or even the width and height of the local image, but it is still HTML5, and it can access the file size. Unfortunately, HTML5 is still not a complete standard and is evenly distributed across all browsers. An alternative solution relies on a Flash, Java, or ActiveX plug-in. No thanks, I will pass. However, another solution is to install the optional PHP cache extension, but it may not depend on your hosting environment. It seems like such a small task, such as overhead.
It seems that all the options are full of troubles, And the task has quickly become a headache. But in Yuda, "No... is another ."
One of the many reasons I love PHP is that it makes seemingly difficult tasks easy. In PHP 5.4, they have made another new configuration instruction set, session. upload_progress.
In this article, I will tell you how this function 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 walk through the four files you created and the tasks to be completed (the upload form, some JavaScript, a little bit of CSS, returns the uploaded status and file ).
Session upload progress
In addition to the general requirements, you can upload files with two tracking steps. You must enable the session. upload_progress.enabled command and the webpage form with the name you specified must have a hidden session. upload_progress.name command. When session. upload_progress.enabled is true (because it is in PHP 5.4 by default, probably exceeds) $ _ POST [session. upload is sent during upload_progress.name, and the file transmission information is an ultra-Global Array in $ _ SESSION.
The output $ _ SESSION array of print_r () will be similar to the following file transfer process:

Array
(
[Upload_progress_myForm] => Array
(
[Start_time] => 1323733740
[Content_length] = & gt; 721127769
[Bytes_processed] = & gt; 263178326
[Done] =>
[Files] => Array
(
[0] => Array
(
[Field_name] => userfile
[Name] => ubuntu-10.04.3-desktop-i386.iso
[Tmp_name] =>
[Error] => 0
[Done] =>
[Start_time] => 1323733740
[Bytes_processed] = & gt; 263178026
)
)
)
)

When you are developing a local or fast network to upload small files, you won't be able to intuitively observe the progress because transfer occurs so fast. In this case, you may want to try to transfer a large file. Make sure that the setting file in your php. ini allows uploading large, specific post_max_size upload_max_filesize commands, and then confirm that they are rational value when you go to production.

Create form
 
I will propose the first file upload form. Just to keep things as simple as possible, such as posting to yourself, only one file can be uploaded at a time. In addition, I will not disturb the upload after saving the file.
The following code is form. php:
01
<? Php
02
If ($ _ SERVER ["REQUEST_METHOD"] = "POST "&&! Empty ($ _ FILES ["userfile"]) {
03
// Move_uploaded_file ()
04
}
05
?>
06
<Html>
07
<Head>
08
<Title> File Upload Progress Bar </title>
09
<Link rel = "stylesheet" type = "text/css" href = "style.css">
10
</Head>
11
<Body>
12
<Div id = "bar_blank">
13
<Div id = "bar_color"> </div>
14
</Div>
15
<Div id = "status"> </div>
16
<Form action = "<? Php echo $ _ SERVER ["PHP_SELF"];?> "Method =" POST"
17
Id = "myForm" enctype = "multipart/form-data" target = "hidden_iframe">
18
<Input type = "hidden" value = "myForm"
19
Name = "<? Php echo ini_get ("session. upload_progress.name");?> ">
20
<Input type = "file" name = "userfile"> <br>
21
<Input type = "submit" value = "Start Upload">
22
</Form>
23
<Iframe id = "hidden_iframe" name = "hidden_iframe" src = "about: blank"> </iframe>
24
<Script type = "text/javascript" src = "script. js"> </script>
25
</Body>
26
</Html>

In this example, the Code actually processes files that have been omitted, making things easier. If you are interested in what such code should look like, check out the article and use the PHP file to upload Timothy Boronczyk.
Provide the webpage title, including the first section after the style sheet. You will find a small set of div elements. Container in the progress bar with the ID card "bar_blank. The file upload progress will be dynamically updated with the ID card "bar_color. The "ID" div displays the uploaded % value.
Submit the settings to a URL with the same hidden iframe elements and set the target vertex. Submit the form to a hidden frame so that you can stay on the same page, and the work done in the background is being done by the visitor. In fact, this is a common practice when "upload an Ajax file", because it directly uses the JavaScript XMLHttpRequest object to send the content of a file is impossible.
In the form, special hidden fields need to be filled in the array $ _ SESSION, followed by a file upload input and submit button. Submitting a form triggers a JavaScript function named startUpload () to define the contained JavaScript file.
The hidden frames at the bottom of the page will publish and import script. js files.
Add some styles
 
Style.css file, the next file, is very straightforward. I define the container size of the progress bar and give it a black edge of 1px as the color of its loading progress bar, and the hidden iframe and progress bar.
01
# Bar_blank {
02
Border: solid 1px #000;
03
Height: 20px;
04
Width: 300px;
05
}
06
07
# Bar_color {
08
Background-color: #006666;
09
Height: 20px;
10
Width: 0px;
11
}
12
13
# Bar_blank, # hidden_iframe {
14
Display: none;
15
}

Client Functions
 
The script. js file is the largest set of files. It contains six functions, which I will discuss below. Many people like to use some functions provided by jQuery. If you want to, you must be free to do so, but I personally prefer the old school practices. Similar to how Japan has a high value for hand-made goods, I just feel that I love code more, if it is myself.
01
Function toggleBarVisibility (){
02
Var e = document. getElementById ("bar_blank ");
03
E. style. display = (e. style. display = "block ")? "None": "block ";
04
}
05
06
Function createRequestObject (){
07
Var http;
08
If (navigator. appName = "Microsoft Internet Explorer "){
09
Http = new ActiveXObject ("Microsoft. XMLHTTP ");
10
}
11
Else {
12
Http = new XMLHttpRequest ();
13
}
14
Return http;
15
}
16
17
Function sendRequest (){
18
Var http = createRequestObject ();
19
Http. open ("GET", "progress. php ");
20
Http. onreadystatechange = function () {handleResponse (http );};
21
Http. send (null );
22
}
23
24
Function handleResponse (http ){
25
Var response;
26
If (http. readyState = 4 ){
27
Response = http. responseText;
28
Document. getElementById ("bar_color"). style. width = response + "% ";
29
Document. getElementById ("status"). innerHTML = response + "% ";
30
31
If (response <100 ){
32
SetTimeout ("sendRequest ()", 1000 );
33
}
34
Else {
35
ToggleBarVisibility ();
36
Document. getElementById ("status"). innerHTML = "Done .";
37
}
38
}
39
}
40
41
Function startUpload (){
42
ToggleBarVisibility ();
43
SetTimeout ("sendRequest ()", 1000 );
44
}
45
46
(Function (){
47
Document. getElementById ("myForm"). onsubmit = startUpload;
48
})();
The toggleBarVisibility () function sets a proper style of "bar_blank" to show or hide the progress bar. Initially, it is hidden, but once the upload starts, it is hidden again when the upload is complete.
The XMLHttpRequest or ActiveXObject created by the createRequestObject () function is based on the objects in the user's browser. This may be what most people expect from jQuery or some other JavaScript frameworks.
SendRequest refers to the file of the progress. php GET request requested by the () function, and then calls the handleResponse () function to process the returned data.
The handleResponse () function processes the File Upload progress from the response progress. php, which is a number between 1 and. I also use the appropriate value to update the "status" DIV. If it is less than 100 of the current %, then I call the native setTimeout () function of JavaScript to change this value appropriately for the second one after updating the request, otherwise, the progress bar and status are hidden and set to "finished ".
The startUpload () function visible in the upload column sets the Update Requirements after sending a delay of 1 second. This small latency is required to start the upload time.
The last feature is a self-executed anonymous function that registers the commit event of the startUpload () form.
 
Real-time progress
 
The last file that is brought together is the progress. php file:
01
<? Php
02
Session_start ();
03
04
$ Key = ini_get ("session. upload_progress.prefix"). "myForm ";
05
If (! Empty ($ _ SESSION [$ key]) {
06
$ Current = $ _ SESSION [$ key] ["bytes_processed"];
07
$ Total = $ _ SESSION [$ key] ["content_length"];
08
Echo $ current <$ total? Ceil ($ current/$ total * 100): 100;
09
}
10
Else {
11
Echo 100;
12
}

The script executes some simple mathematical transmission of the number of bytes divided by the total file size, multiplied by 100, rounded to a percentage point.
For the transfer information, type the value of the hidden session. upload_progress.prefix field that Concatenates the value of a session. upload_progress.name command. Because my form has passed "myForm", the key to the meeting is to determine ini_get ("session. upload_progress.prefix "). "MyForm ".
Here is the progress bar of an action:


Fine-tuned Behavior
PHP provides some additional instructions to help you fine-tune the behavior of meeting uploads, which you should know. For example, session. upload_progress.cleanup, which is an additional meeting set to 1 by default and uploaded data immediately after cleaning. You must be careful to avoid potential competition conditions.
Let's take another look. In code progress. php, you will find that I check whether the [$ key] in $ _ SESSION is empty or does not continue. My JavaScript function is triggered from the returned results every time the second progress. php is less than 100. If session. upload_progress.cleanup is enabled and my script obtains the 99% and 1 1/2-second of the upload, the upload is complete. $ _ SESSION [$ key] will not have the next check. If I didn't take it into consideration, then my JavaScript function may keep shooting even after the upload is complete.
The other two commands are session. upload_progress.freq and session. upload_progress.min_freq. Both parties determine how meetings should be updated. The frequency value can be any byte (100) or the percentage of the total number of bytes (2%. Min_freq indicates the minimum number of seconds between updates within a few seconds. Obviously, if min_freq is updated every 1 second, it will be meaningless to check your JavaScript every 100 milliseconds.
Conclusion: www.2cto.com
Now you should have a file upload progress bar with a strong grasp of how to create a file upload progress bar using the conference upload progress function. Moving forward, I encourage you to upload multiple files in an experiment and choose to cancel the usage progress upload $ _ SESSION [$ key to drum up your mind ["cancel_upload",], or any other ideas. Please refer to your experience and suggestions for improvement.

Author: newcnzz
 

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.