search
HomeBackend DevelopmentPHP TutorialExample sharing Ajax upload file progress bar Codular

Example sharing Ajax upload file progress bar Codular

Dec 26, 2017 am 11:18 AM
ajaxuploaddocument

Now, people like to do other things while browsing a web page without leaving the web page, which is usually achieved through ajax. Most of the time, people use jQuery to achieve it, but with the advancement of browsers, people can't This needs to be done. This article mainly introduces the relevant information of Ajax upload file progress bar Codular. Friends who need it can refer to it. I hope it can help everyone.

Here we will explain how to upload a file to the server without leaving the page, we will use the same backend PHP code that we used in our previous article. This script will upload the file to the server, At the same time, the upload progress is displayed, and finally the link address of the uploaded file is returned. 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 will start with the HTML structure, then the JavaScript, then I will give you the PHP code, this part is adapted from Previous Tutorial - There won't be much explanation of the PHP code.

HTML

We only need to use two input boxes, one is the file type file, and the other is just a button button, so that we can listen to it being clicked to send File upload request. We'll also have a p that we change the width to highlight the status of the upload.

As shown below:


<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS File Upload with Progress</title>
  <style>
  .container {
    width: 500px;
    margin: 0 auto;
  }
  .progress_outer {
    border: 1px solid #000;
  }
  .progress {
    width: 20%;
    background: #DEDEDE;
    height: 20px; 
  }
  </style>
</head>
<body>
  <p class=&#39;container&#39;>
    <p>
      Select File: <input type=&#39;file&#39; id=&#39;_file&#39;> <input type=&#39;button&#39; id=&#39;_submit&#39; value=&#39;Upload!&#39;>
    </p>
    <p class=&#39;progress_outer&#39;>
      <p id=&#39;_progress&#39; class=&#39;progress&#39;></p>
    </p>
  </p>
  <script src=&#39;upload.js&#39;></script>
</body>
</html>

You will see that we wrote a little progress bar style and added a script file at the bottom to handle file upload and progress Strip display.

JavaScript

First, we need to get the tags we are going to use, they are already tagged with ids.


var _submit = document.getElementById(&#39;_submit&#39;), 
_file = document.getElementById(&#39;_file&#39;), 
_progress = document.getElementById(&#39;_progress&#39;);

Next step, add a click event to _submit to upload the file we selected. To do this, we will use the addEventListener method and let it call the upload method after clicking the button.


_submit.addEventListener(&#39;click&#39;, upload);

Now we can continue processing the upload, there are the following steps:

  1. Check the selected file

  2. Dynamically create file data to be sent

  3. Create XMLHttpRequest through js

  4. Upload files

Check the selected file

Our file input box _file has a parameter files to query the selected file queue-if you set the multiple parameter, you can select multiple files. We do it simply 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 a file has been selected, we will assume that there is a file , please remember that the index of the array starts with 0.

Dynamicly create the file data to be sent

For this, we need to use FormData and add the data to it. Next, we can send our FormData in the request generated in step 3. The append method we use, the first parameter is similar to the name attribute of the input box, and the second parameter is the value. Here, we set value For the first file we select.


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

We will use it when sending data to the server later.

Pass Upload script creates XMLHttpRequest

This part is very basic, we will create a new XMLHttpRequest and set some settings. First we will modify the value of onreadystatechange to define the callback function when requesting a state change. This method will check readyState when the state changes to make sure the value is what we want - in this case it is 4, Indicates that the request is completed.

In the second step, we will add the progress event on the upload attribute. In this way 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: &#39;error&#39;,
        data: &#39;Unknown error occurred: [&#39; + request.responseText + &#39;]&#39;
      };
    }
    console.log(resp.status + &#39;: &#39; + resp.data);
  }
};

When the request is successful, we use try...catch to wrap the process of parsing the return value. If the parsing fails, we will create our own return object so that the subsequent code will not report an error. You can decide how to handle the return value. Here we just output it to the console.

Now let's deal with the progress bar:


##

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

It's a little complicated here , we listen to an event. The event object has two attributes that we are more concerned about. loaded and total. loaded represents the value that has been uploaded to the server, and total represents 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 according to your needs.

Upload file

Now we can send the request, we will make a POST request to a file called upload.php and use the send() method with the parameter data so we can send the data:


request.open(&#39;POST&#39;, &#39;upload.php&#39;);
request.send(data);

The complete JavaScript code is given below:


var _submit = document.getElementById(&#39;_submit&#39;), 
_file = document.getElementById(&#39;_file&#39;), 
_progress = document.getElementById(&#39;_progress&#39;);
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(&#39;click&#39;, upload);

Now comes PHP...

PHP

This is the code we used, you will notice some differences, mainly that we use the top JSON method to return the value and output it as JSON format. This PHP is the same as the code in the previous article, which is also This means that this method is only applicable to PNG images smaller than 500Kb. In addition, the success message will return the path of the uploaded file:


<?php
// Output JSON
function outputJSON($msg, $status = &#39;error&#39;){
  header(&#39;Content-Type: application/json&#39;);
  die(json_encode(array(
    &#39;data&#39; => $msg,
    &#39;status&#39; => $status
  )));
}
// Check for errors
if($_FILES[&#39;SelectedFile&#39;][&#39;error&#39;] > 0){
  outputJSON(&#39;An error ocurred when uploading.&#39;);
}
if(!getimagesize($_FILES[&#39;SelectedFile&#39;][&#39;tmp_name&#39;])){
  outputJSON(&#39;Please ensure you are uploading an image.&#39;);
}
// Check filetype
if($_FILES[&#39;SelectedFile&#39;][&#39;type&#39;] != &#39;image/png&#39;){
  outputJSON(&#39;Unsupported filetype uploaded.&#39;);
}
// Check filesize
if($_FILES[&#39;SelectedFile&#39;][&#39;size&#39;] > 500000){
  outputJSON(&#39;File uploaded exceeds maximum upload size.&#39;);
}
// Check if the file exists
if(file_exists(&#39;upload/&#39; . $_FILES[&#39;SelectedFile&#39;][&#39;name&#39;])){
  outputJSON(&#39;File with that name already exists.&#39;);
}
// Upload file
if(!move_uploaded_file($_FILES[&#39;SelectedFile&#39;][&#39;tmp_name&#39;], &#39;upload/&#39; . $_FILES[&#39;SelectedFile&#39;][&#39;name&#39;])){
  outputJSON(&#39;Error uploading file - check destination is writeable.&#39;);
}
// Success!
outputJSON(&#39;File uploaded successfully to "&#39; . &#39;upload/&#39; . $_FILES[&#39;SelectedFile&#39;][&#39;name&#39;] . &#39;".&#39;, &#39;success&#39;);

如果将所有内容都放在一起,您应该可以将文件上传到您期望的位置,并在浏览器的控制台内成功返回。

结束语

还有一些比较容易而又有效的方式来增强用户体验.通过将文件队列的多个文件加入到FormData,可以实现多文件上传. 有一点要说明,如果你是在本地做测试,你可能没办法看到进度条逐步变化,这取决于你本地机器的上传速度,我建议在服务器上使用较大的png文件做测试.

相关推荐:

PHP利用APC模块实现上传进度条的实例分享

实例讲解Ajax实现简单带百分比进度条

JavaScript控制进度条的实例分析

The above is the detailed content of Example sharing Ajax upload file progress bar Codular. For more information, please follow other related articles on the PHP Chinese website!

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
How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

How can you trace session activity in PHP?How can you trace session activity in PHP?Apr 27, 2025 am 12:10 AM

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

How can you use a database to store PHP session data?How can you use a database to store PHP session data?Apr 27, 2025 am 12:02 AM

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software