Track upload progress PHP and javascript_php tutorials

Source: Internet
Author: User
Tags file upload progress bar
A question that has plagued web developers for years is how to add real-time information to their applications, such as file upload progress bars. Users are impatient; they don't want to wait while the browser is doing some, wondering whether it has been frozen or if they have a slow connection. Provides a progress indicator that provides users with useful information and lets them know exactly what is going on.
The first thought that you might want to do this can easily be calculated by first getting the file size from the user's computer, and then executing the directory where the file is being uploaded on the server for some simple calculations. On the second idea, you will find that things are not that simple.
JavaScript can access the file's name, type, and even the width and height of the local image, but it is up to HTML5, and it can access the size of the file. Unfortunately, HTML5 is still not a complete standard and is evenly distributed across all browsers that are not supported. An alternative solution is to rely on a Flash,java or ActiveX plugin, no thanks, I will pass. However, another workaround is to install an optional PHP cache extension, but it may not depend on your hosting environment, it seems like such a small task, such as overkill.
It seemed as if all the options were filled with nuisance, and the task had quickly become a headache. But in Yoda's words, "no ... is another. ”
One of the many reasons I love PHP is that it makes seemingly difficult tasks easier. 5.4 php, they do another new configuration instruction set, session.upload_progress.
In this article, I'll show you how this feature can be used to create a simple upload progress bar without any external libraries or browser dependencies. I'll first discuss how it works, and then I walk through the four files you create, the tasks you need to accomplish (upload form, some JavaScript, a little bit of CSS, return upload status and files).
Session Upload Progress
In addition to the general requirements, allow uploading of files, there are two tracking progress. You must have a hidden farm session.upload_progress.name directive in a Web form that has the SESSION.UPLOAD_PROGRESS.ENABLED directive enabled and the name you specify. When Session.upload_progress.enabled is true (because it is default in PHP 5.4, probably exceeds) of $ _post [session.upload_progress.name during sending uploads, the file transfer information is in $ _ The hyper-Global array for the session.
The Print_r () output of the $ _session array will resemble the following in the file transfer process:

Array
(
[Upload_progress_myform] = = Array
(
[Start_time] = 1323733740
[Content_length] = 721127769
[Bytes_processed] = 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] = 263178026
)
)
)
)

When you are developing a local or fast network to upload small files, you will not be able to visually observe the progress as the transfer occurs so quickly. In this case, you may want to try to transfer a large file. Make sure that the settings file in your php.ini allows you to upload large, specific post_max_size upload_max_filesize instructions and then confirm that they are the value of reason when you go to production.

Create a form

I will present the first file to upload the form. Just to keep things as simple as possible, such as posting to yourself, only one file upload can be processed at a time. Also, I won't bother to save the file after it has been uploaded.
Here is the code form.php:
01
02
if ($_server["request_method"] = = "POST" &&!empty ($_files["UserFile"]) {
03
Move_uploaded_file ()
04
}
05
?>
06

07

08
File Upload Progress Bar
09

10

11

12

13

14

15

16

23

24

25

26

In this example the code actually handles the files that have been omitted and makes things simple. If you are interested in what such code should look like, check out the article with PHP file to upload Timothy Boronczyk.
Provide the title of the Web page, including the header section after the style sheet, and you will find a small collection of DIV elements. The container of the progress bar with the identity card "Bar_blank". With the identity card "Bar_color" The file uploads the progress of the dynamically updated files. The "Identity" div will display the value of the upload%.
Sets the form to submit the same URL to a hidden IFRAME element and its target attribute point. Submit the form to a hidden frame that keeps you on the same page while the work done in the background is being visited by the visitor. In fact, this is a common practice when doing "Ajax file uploads" because it is not possible to send the contents of a file directly using JavaScript's XMLHttpRequest object.
In the form of a special hidden field that needs to be populated with the array $ _session appears, followed by a file on the transmit and submit button. Submitting a form will trigger a JavaScript function named Startupload () that will define the included JavaScript file.
In the form of 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 size of the progress bar container and give it a 1px black edge, as it loads the color of the progress bar, and hides the 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 Features

Script.js files are the largest set of files. It contains six major features that I will discuss below. Many people like to use jquery to provide some features, if you want, you certainly are free to do so, but I personally prefer the old-fashioned approach. Similar to how the Japanese place for handmade goods value higher, I just feel more love code, if it is my own.
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);};
21st
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 an appropriate style of "Bar_blank" to show or hide the progress bar. Initially, it is hidden, but once the upload starts it will show that the upload is complete and hidden again.
The Createrequestobject () function creates an object on the user-based browser of the XMLHttpRequest or ActiveXObject. This is probably the feature that most people expect from jquery or some other JavaScript framework.
SendRequest the () function requests the progress.php GET request file, and then calls the Handleresponse () function to process the returned data.
The Handleresponse () function handles the file upload progress from the response progress.php which will be a number between 1-100. I also updated the "status" DIV with the appropriate values. If the current is below 100, then I call the native settimeout () function of JavaScript to make another update request after the second of 1 can adjust this value appropriately, otherwise I hide the progress bar again and the status is set to "done".
The Startupload () function that is visible in the upload bar causes the request to update after a delay of 1 seconds is sent. This little delay is needed in order to give the upload time to start.
The last feature is a self-executing anonymous function that registers the commit event for the startupload () Form.

Real-time Progress

Bringing everything together. The last file is progress.php file:
01
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 performs some simple mathematically transmitted bytes divided by the total file size, multiplied by 100, rounded to a percentage point.
Information about the transfer type the value of a Session.upload_progress.prefix instruction value in series for the Hidden session.upload_progress.name field. Because my form passed the "MyForm", the key to the meeting was to determine Ini_get ("Session.upload_progress.prefix"). "MyForm".
Here is an action for the progress bar:


Fine-tuning behavior
PHP provides some additional instructions to help fine tune the behavior of the meeting uploads that you should know. For example, Session.upload_progress.cleanup, which is the default setting of 1, is the additional meeting that uploads data immediately after the cleanup is complete. You have to be careful to avoid the potential competitive conditions.
Take a look again, in code progress.php, you will find that I check to see if $ _session in the [$ key] is empty or not to continue before. My JavaScript feature triggers, from the returned results, each as long as the second progress.php is less than 100. If Session.upload_progress.cleanup is enabled and my script gets uploaded 99% and 1 1/2-second after the upload is completed, the _session [$ key] will not exist for the next check. If I don't take that into account then my JavaScript function may keep shooting even after uploading is complete.
The other two instructions are session.upload_progress.freq, and session.upload_progress.min_freq both sides determine how often meetings should be updated. The frequency value that can be in either byte (that is, 100), or as a percentage of the total number of bytes (that is, 2%). The value min_freq in seconds, and represents the minimum number of seconds between updates. Obviously, if min_freq updates every 1 seconds, it would be pointless to check your javascript every 100 milliseconds.
Summary www.2cto.com
You should now have a solid grasp on how to create a file upload progress bar using the conferencing upload progress feature. Go ahead, I encourage you to experiment with uploading multiple files, choosing to cancel the progress of uploading $ _session [$ key can muster up your mind ["cancel_upload",], or any other idea. Please comment on your experience and improvements.

Author: newcnzz

http://www.bkjia.com/PHPjc/478020.html www.bkjia.com true http://www.bkjia.com/PHPjc/478020.html techarticle a question that has plagued web developers for years is how to add real-time information to their applications, such as file upload progress bars. Users are impatient; they don't want to sit and browse ...

  • Related Article

    E-Commerce Solutions

    Leverage the same tools powering the Alibaba Ecosystem

    Learn more >

    Apsara Conference 2019

    The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

    Learn more >

    Alibaba Cloud Free Trial

    Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

    Learn more >

    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.