Now, people like to do something else while browsing the web without leaving the page, which is usually done through Ajax. In most cases, people use jquery, but with the progress of the browser, people do not need to do this, This article mainly introduces the Ajax upload file progress bar Codular related information, the need for friends can refer to, hope to help everyone.
Here we'll show you how to upload a file to the server without leaving the page, and we'll use the same backend PHP code that we used in our previous article. The script uploads the file to the server, displays the upload progress, and eventually returns the link address of the uploaded file. In some cases, you may want to return the ID of the uploaded file or other application information. Note: This code does not support older IE browsers, through can I use we only support ie10+
Let ' s Code
We'll start with the HTML structure, then JavaScript, and then I'll give you the PHP code, which is partially adapted from the previous tutorial-there won't be much explanation for the PHP code.
Html
We only need to use two input boxes, one for file type, and one for button, so we can listen to it being clicked to send a file upload request. We'll also have a p and we'll change the width to highlight the upload status.
As shown below:
<!doctype html>
You'll see that we've written a little progress bar style and added a script file at the bottom to handle file uploads and progress bar displays.
Javascript
First, we need to get the tags we're going to use, they've been tagged with ID.
var _submit = document.getElementById (' _submit '), _file = document.getElementById (' _file '), _progress = document.getElementById (' _progress ');
Next, add a click event to _submit to upload the file of our choice. To do this, we'll use the AddEventListener method, and then click the button and let it call the upload method.
_submit.addeventlistener (' click ', upload);
Now we can proceed with the upload, with the following steps:
Check for selected files
Dynamic creation of file data to be sent
Create XMLHttpRequest with JS
Uploading files
Check for selected files
Our file input box _file has a query for the parameters of the selected file queue files-If you set the multiple parameter you will be able to select multiple files. We do a simple check to determine if the array length is greater than 0, then continue, or return directly.
if (_file.files.length = = = 0) { return;}
Now that we can make sure that a file is selected, we will assume that there is a file, remember that the index of the arrays begins with 0.
Dynamic creation of file data to be sent
To do this, we need to use Formdata and add the data to it. Next, we can send our formdata in the request generated by step 3rd. We use the Append method, the first parameter is similar to the Name property of the input box, and the second parameter is the value. Here, we set value to the first file we selected.
var data = new FormData ();d ata.append (' Selectedfile ', _file.files[0]);
When you send data to the server later, we will use it.
Create XMLHttpRequest by uploading scripts
This section is very basic and we will create a new one XMLHttpRequest and set some settings. First we will modify onreadystatechange the value to define the callback function when the request state changes. The method will check the readystate when the state changes, making sure that the value is what we want-in this case, 4, the request is complete.
In the second step, we will add the progress event on the upload property. So we can get the upload progress to update the progress bar.
var request = new XMLHttpRequest (); request.onreadystatechange = function () { if (request.readystate = = 4) { try { C2/>var resp = json.parse (request.response); } catch (e) { var resp = { status: ' Error ', data: ' Unknown error occurred: [' + Request.responsetext + '] ' }; } Console.log (Resp.status + ': ' + resp.data); }};
When the request succeeds, we use the Try ... catch package to parse the return value of the process, if the parse fails, we will create our own return object so that the subsequent code can not error. You can decide what to do with the return value, here we just output it to the console.
Now let's deal with the progress bar:
Request.upload.addEventListener (' Progress ', function (e) { _progress.style.width = Math.ceil (e.loaded/e.total) * + '% ';}, False);
There's a little bit of complexity here, we listen to an event that has two properties that we're concerned about, loaded and total.loaded represent the values that have been uploaded to the server, total represents the sum of the values to be sent, and we can calculate a percentage based on these two values. To set the width of the progress bar.
Note: No animated effects are added here, but you can customize the animations as needed.
Uploading files
Now we can send the request, we will send the request to a file named upload.php, and use the Send () method, the parameter is data, so that we can be sent:
Request.open (' POST ', ' upload.php '); request.send (data);
The complete JavaScript code is given below:
var _submit = document.getElementById (' _submit '), _file = document.getElementById (' _file '), _progress = document.getElementById (' _progress '); var upload = function () { if (_file.files.length = = = 0) { return; } var data = new FormData (); Data.append (' Selectedfile ', _file.files[0]); var request = new XMLHttpRequest (); Request.onreadystatechange = function () { if (request.readystate = = 4) { try { var resp = json.parse ( request.response); } catch (e) { var resp = { status: ' Error ', data: ' Unknown error occurred: [' + Request.responsetext + '] '
}; } Console.log (Resp.status + ': ' + resp.data); } }; Request.upload.addEventListener (' Progress ', function (e) { _progress.style.width = Math.ceil (e.loaded/e.total) * + '% '; }, False); Request.open (' POST ', ' upload.php '); Request.send (data);} _submit.addeventlistener (' click ', upload);
Now to PHP ...
Php
This is the code that we use, and you'll notice some differences, mainly because we use the top-most JSON method to return values as JSON-formatted output. This PHP is the same as the code in the previous article, which means that the method only works with PNG images less than 500Kb. In addition, The success information returns the path to the uploaded file:
<?php//Output jsonfunction Outputjson ($msg, $status = ' error ') {header (' Content-type:application/json '); Die (Json_encode (' data ' = $msg, ' status ' = $status))); Check for Errorsif ($_files[' selectedfile ' [' Error '] > 0) {outputjson (' An error ocurred when uploading. ');} if (!getimagesize ($_files[' selectedfile ' [' tmp_name '])) {Outputjson (' Please ensure is uploading an image. ');} Check Filetypeif ($_files[' selectedfile ' [' type ']! = ' image/png ') {Outputjson (' unsupported filetype uploaded. ');} Check Filesizeif ($_files[' selectedfile ' [' Size '] > 500000) {outputjson (' File uploaded exceeds maximum upload size. ');} Check if the file Existsif (file_exists (' upload/'. $_files[' selectedfile ' [' name '])) {Outputjson (' file with ' already exists. ');} Upload Fileif (!move_uploaded_file ($_files[' selectedfile '] [' tmp_name '], ' upload/'. $_files[' selectedfile ' [' Name ']) {Outputjson (' Error uploading file-check destination is writeable. ');} Success!outputjson (' File uploaded successfully to ' '. ' Upload/'. $_files[' selectedfile ' [' Name ']. '. ', ' success ');
If you put everything together, you should be able to upload the file to your desired location and return it successfully within the browser's console.
Conclusion
There are also some easier and more effective ways to enhance the user experience. multiple file uploads can be implemented by adding multiple files to the Formdata file queue. One thing to note is that if you are testing locally, you may not be able to see a gradual change in the progress bar, depending on the upload speed of your local machine, I recommend using a larger PNG file on the server for testing.