search
HomeWeb Front-endJS TutorialHow to implement progress bar for uploading files with Ajax Codular

This time I will show you how Ajax implements the progress bar Codular for uploading files. What are the precautions for Ajax to implement the progress bar Codular for uploading files. Here is a practical case, let's take a look.

Nowadays, people like to do some 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 than don't need to do this. Here we will cover how to upload files to the server without leaving the page, we will use the same backend PHP code that we used in our previous article. The The script will upload the file to the server, display the upload progress, and finally return 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 The ie browser, through Can I use we only support ie10+

Let's Code

We will start with the HTML structure, then the JavaScript, I will then provide you with the PHP code, which is adapted from the 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:

nbsp;html>


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


  <p>
    </p><p>
      Select File: <input> <input>
    </p>
    <p>
      </p><p></p>
    
  
  <script></script>

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

JavaScript

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

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

Next step, give_ submit adds a click event 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('click', upload);

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

  1. Check the selected file

  2. Dynamicly create the file data to be sent

  3. Through js Create XMLHttpRequest

  4. Upload file

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 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 that we can ensure that a file is 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

To do 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 the same as the input The name attribute of the box is similar, the second parameter is the value. Here, we set value to the first file we selected.

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

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

Creating XMLHttpRequest via upload script

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 ensure that the value is what we want - in In this example, it is 4, which means 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 and use it 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 After 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('progress', function(e){
  _progress.style.width = Math.ceil(e.loaded/e.total) * 100 + '%';
}, false);

这里有一点点复杂,我们监听一个事件,该事件对象有两个我们比较关注的属性,loaded和total.loaded表示已经上传到服务器端的数值,total表示要发送的总数值,我们可以根据这两个值计算一个百分比,来设置进度条的宽度.

Note: 这里没有加入任何动画特效,但你可以根据需要自定义动画效果.

上传文件

现在我们可以发送请求,我们将通过POST请求到一个名为upload.php的文件,并使用send()方法,参数为data,这样我们就可以发送数据:

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

下面给出完整的JavaScript代码:

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

现在到了PHP...

PHP

这是我们使用的代码,你将注意到一些区别,主要是我们用最上面的JSON方法来返回值都作为JSON格式输出.这个PHP与之前文章中的代码相同,这也就意味着该方法只适用于小于500Kb的PNG图片.此外,成功信息将返回已上传文件的路径:

<?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,
    'status' => $status
  )));
}
// Check for errors
if($_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 filetype
if($_FILES['SelectedFile']['type'] != 'image/png'){
  outputJSON('Unsupported filetype uploaded.');
}
// Check filesize
if($_FILES['SelectedFile']['size'] > 500000){
  outputJSON('File uploaded exceeds maximum upload size.');
}
// Check if the file exists
if(file_exists('upload/' . $_FILES['SelectedFile']['name'])){
  outputJSON('File with that name already exists.');
}
// Upload file
if(!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');

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

结束语

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

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

ajax的三级联动菜单栏如何实现

ajax数据处理步骤详解(附代码)

The above is the detailed content of How to implement progress bar for uploading files with Ajax 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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

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

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.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

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