Home >Backend Development >PHP Tutorial >Track Upload Progress PHP and JavaScript_PHP Tutorial

Track Upload Progress PHP and JavaScript_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 17:53:42958browse

A problem that has plagued web developers for years is how to add real-time information, such as file upload progress bars, to their applications. Users are impatient; they don't want to sit around waiting while the browser is doing something, wondering whether it has frozen or if they have a slow connection. A progress indicator is provided to provide useful information to the user and let them know what exactly is going on.
First thought you might want to accomplish this can be done easily by first getting the size of the file from the user's computer and then performing some simple calculations on the server where the directory is located where the file is being uploaded. Regarding the second thought, you will find that things are not that simple.
JavaScript can access the file's name, type, and even the width and height of native images, but it wasn't until HTML5 that it could access the file's size. Unfortunately, HTML5 is still not a complete standard and is evenly distributed across all browsers. An alternative solution is to rely on a Flash, Java or ActiveX plug-in, no thanks I'll pass. However, another solution is to install the optional PHP caching extension, but depending on your hosting environment it may seem like such a small task as overkill.
It seems as if all the options are filled with nuisances and the task has quickly become a headache. But in Yoda's words, "No...it's the other one."
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 show you how this functionality can be used to create a simple upload progress bar without any external library or browser dependencies. I'll first discuss how it works, and then I'll walk through the four files you create that need to complete the task (upload the form, some JavaScript, a little CSS, return the upload status and file).
Session upload progress
In addition to the general requirements to allow file uploads, there are two to track progress. The session.upload_progress.enabled directive must be enabled and the name you specify in the web form must have a hidden field in the session.upload_progress.name directive. When session.upload_progress.enabled is true (as it is by default in PHP 5.4, presumably beyond) an upload is sent during $_POST [session.upload_progress.name], and the file transfer information is in the $_SESSION superglobal array.
The output of print_r() for the $_SESSION array will resemble the following during a file transfer:

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
                        )
                )
        )
)

当您正在开发本地或快速网络上传小文件,你不会是能够直观地观察到的进展,因为转让发生如此之快。在这种情况下,你可能想尝试传送一个大文件。确保在你的php.ini的设置文件允许上传大,具体的post_max_size 的upload_max_filesize指令,然后确认他们是理智的价值,当你去生产。

创建表单
 
我会提出的第一个文件上传表单。只是为了保持尽可能简单的事情,例如将张贴到自己,一次只能处理一个文件上传。此外,我不会打扰保存文件后,它已上载。
下面是代码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
" method="POST"
17
id="myForm" enctype="multipart/form-data" target="hidden_iframe">
18
19
name="">
20


21

22

23

24

25

26

The files the code actually handles in this example have been omitted to make things simpler. If you're interested in what such code should look like, check out the article Uploading Files with PHP by Timothy Boronczyk.
After providing the title of the page and including the stylesheet in the header section, you'll find a small collection of div elements. Container for the progress bar with the ID "bar_blank" grid. The grid with ID "bar_color" will dynamically update the file upload progress. The "identity" div will display the uploaded % value.
Set the form submission to the same URL as a hidden iframe element and set its target attribute point. Submit the form into a hidden frame, allowing you to stay on the same page while the work is being done in the background for the visitor. In fact, this is a common practice when doing "Ajax file upload" as it is not possible to send the contents of a file directly using JavaScript's XMLHttpRequest object.
In the form, special hidden fields need to be populated in the array $_SESSION to appear, followed by a file upload input and submit button. Submitting the form will trigger a JavaScript function called startUpload() which will be defined in the included JavaScript file.
A hidden frame form at the bottom of the page will publish and import the script.js file.
Add some styling

The style.css file, the next file, is very straightforward. I define the size of the progress bar container and give it a 1px black border as the color of its loading progress bar, and hide 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 functions

The script.js files are the largest set of files. It contains six major features, which I will discuss below. A lot of people like to use some of the features jQuery provides, and you're certainly free to do so if you want, but I personally prefer the old school approach. Similar to how Japan places a higher value on handmade goods, I just feel more in love with code if it were 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 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 on the "bar_blank" grid to show or hide the progress bar. Initially it shows up hidden but once the upload starts it will show up hidden again when the upload is complete.
The createRequestObject() function creates an XMLHttpRequest or ActiveXObject object based on the user's browser. This is probably what most people expect from jQuery or some other JavaScript framework.
The sendRequest() function requests the progress.php GET requested file, and then calls the handleResponse() function to process the returned data.
The handleResponse() function handles the response from progress.php which will be a number between 1-100 depending on the file upload progress. I also update the "status" DIV with the appropriate values. If the current% is below 100 then I call JavaScript's native setTimeout() function which will adjust this value appropriately after 1 second of another update request, otherwise I hide the progress bar again and set the status to "Done".
The startUpload() function makes the upload bar visible after sending an update request after a 1 second delay. This small delay is needed in order to give the upload time to start.
The last function is a self-executing anonymous function that registers the startUpload() form's submit event.

Real-time progress

The last file that brings everything together is the 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 09
}
10
else {
11
echo 100;
12
}

The script performs some simple math by dividing the number of bytes transferred by the total file size, multiplying by 100, and rounding to give percentage points.
For information about the transfer type the value of a session.upload_progress.prefix directive concatenated with the value of the hidden session.upload_progress.name field. Because my form passes "myForm", the session key is determined by ini_get("session.upload_progress.prefix"). "myForm".
Here is a screenshot of the progress bar of an action:

Track Upload Progress PHP and JavaScript_PHP Tutorial
Fine-tuned behavior
PHP provides some additional directives to help fine-tune the behavior of meeting uploads that you should be aware of. For example, session.upload_progress.cleanup, which is set to 1 by default, uploads additional session data immediately after cleanup is completed. You have to be careful to avoid potential race conditions.
Take another look at the code in progress.php and you'll notice that I check to see if $_SESSION[$key] is empty or not before continuing. My JavaScript function fires as long as the results returned from the second progress.php are less than 100. If session.upload_progress.cleanup is enabled and my script gets 99% of the upload done and 1 1/2-second later the upload is complete $_SESSION[$key] will not exist next check. If I didn't take that into account, then my JavaScript function might keep firing even after the upload is complete.
The other two directives are session.upload_progress.freq, and session.upload_progress.min_freq both determine how often the session should be updated. The frequency value can be either a byte (i.e. 100), or a percentage of the total number of bytes (i.e. 2%). Value min_freq in seconds and represents the minimum number of seconds between updates. Obviously, if min_freq updates every 1 second, it would be pointless to check your javascript every 100 milliseconds.
Summarywww.2cto.com
You should now have a firm grasp of how to create a file upload progress bar using the meeting upload progress feature. Going forward, I encourage you guys to experiment with uploading multiple files, choosing to cancel the progress upload using the $_SESSION[$ key to brainstorm["cancel_upload",], or any other ideas that come to mind. Please comment on your experience and improvements.

Author: newcnzz

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478020.htmlTechArticleA problem that has vexed web developers for years is how to add things like file upload progress to their applications Article, real-time information. Users are impatient; they don’t want to sit around waiting while browsing...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn