Ajax Upload File progress bar Codular, ajaxcodular

Source: Internet
Author: User

Ajax Upload File progress bar Codular, ajaxcodular

Nowadays, people like to do other things without leaving the webpage while browsing the webpage, which is usually implemented through ajax. in most cases, jQuery is used for implementation, but with the improvement of browsers, people do not need to do this. here we will introduce how to upload files to the server without leaving the page. We will use the same backend PHP code as we used in previous articles. this script uploads the file to the server, displays the upload progress, and 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. We only support ie10 + through Can I use.

Let's Code

We will start with the HTML structure, followed by JavaScript, and then I will provide you with PHP code, which is adapted from the previous tutorial-there will not be much explanation of PHP code.

HTML

We only need to use two input boxes, one of which is a file type, and the other is a button, so that we can monitor it and send a file upload request by clicking it. We will also have a div where we change the width to highlight the upload status.

As follows:

<!doctype html>

You will see that we have written a little progress bar style, and added a script file at the bottom to process file uploads and progress bar display.

JavaScript

First, we need to get the tags we are going to use. They are already marked with IDs.

var _submit = document.getElementById('_submit'), _file = document.getElementById('_file'), _progress = document.getElementById('_progress');

Next, add a click event to _ submit to upload the selected file. For this reason, we will use the addEventListener method and click the button to call the upload method.

_submit.addEventListener('click', upload);

Now, we can proceed with the upload process by taking the following steps:

  1. Check selected files
  2. Dynamically create file data to be sent
  3. Create XMLHttpRequest using js
  4. Upload files

Check selected files

In our file input box _ file, there is a query for the parameters of the selected file queue files-if you set the multiple parameter, you can select multiple files. let's make a simple check and judge. If the length of the array is greater than 0, continue; otherwise, return directly.

if(_file.files.length === 0){  return;}

Now, we can ensure that we have selected a file. We will assume that there is a file, please remember that the index of the array starts with 0.

Dynamically create file data to be sent

Therefore, we need to use FormData and add the data to it. next, we can send our FormData in the request generated in step 1. we use the append method. The first parameter is similar to the name attribute of the input box, and the second parameter is the value. here, we set the value to the first file we selected.

var data = new FormData();data.append('SelectedFile', _file.files[0]);

When you send data to the server later, we will use it.

Create XMLHttpRequest using the upload script

This part is very basic and we will create a newXMLHttpRequestAnd set some settings. First, we will modifyonreadystatechangeTo define the callback function when the Request status changes. this method checks readyState when the status changes to make sure that the value is what we want-in this example, 4 indicates that the request is complete.

Step 2: add the progress event on the upload attribute so that we can get the upload progress to update the progress bar.

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

When the request is successful, we use try... if the catch package fails to parse the returned value, we will create our own return object so that no error is reported in the subsequent code. you can decide how to handle the returned value. Here we just output it to the console.

Now let's handle the progress bar:

request.upload.addEventListener('progress', function(e){  _progress.style.width = Math.ceil(e.loaded/e.total) * 100 + '%';}, false);

This is a little complicated. We listen to an event. This event object has two attributes that we are concerned about, loaded and total. loaded indicates the value that has been uploaded to the server, and total indicates the total value to be sent. We can calculate a percentage based on these two values to set the width of the progress bar.

Note: No animation effects are added here, but you can customize the animation effects as needed.

Upload files

Now we can send a request. We will send a POST request to a file named upload. php and use the send () method. The parameter is data, so that we can send data:

request.open('POST', 'upload.php');request.send(data);

The complete JavaScript code is provided 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) * 100 + '%';  }, false);  request.open('POST', 'upload.php');  request.send(data);}_submit.addEventListener('click', upload);

Now PHP...

PHP

This is the code we use. You will notice some differences, mainly because we use the top JSON method to return values as JSON format output. this PHP is the same as the code in the previous article, which means this method is only applicable to PNG images smaller than kb. in addition, the successful information will return the path of the uploaded file:

<?php// Output JSONfunction outputJSON($msg, $status = 'error'){  header('Content-Type: application/json');  die(json_encode(array(    '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 you are 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 that name 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 all the content together, you can upload the file to your desired location and return it in the browser console.

Conclusion

There are also some easy and effective ways to enhance user experience. by adding multiple files in the file queue to FormData, you can upload multiple files. it should be noted that if you are testing locally, you may not be able to see the progress bar gradually changing, depending on the upload speed of your local machine, I suggest using a large png file on the server for testing.

The above is the Ajax Upload File progress bar Codular introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave a message and the editor will reply to you in time. Thank you very much for your support for the help House website!

Related Article

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.