search
HomeWeb Front-endJS TutorialAjax upload file progress bar Codular

Ajax upload file progress bar Codular

May 22, 2018 pm 02:49 PM
ajaxschedule

This article mainly introduces the relevant information of Ajax upload file progress bar Codular. Friends who need it can refer to it

Now, people like to do other things while browsing the web without leaving the web page. Usually it is achieved through ajax. Most of the time, people use jQuery to achieve it, but with the advancement of browsers, people don't 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 we used in our previous article. The script will upload the file to the server, display the upload progress, and eventually 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 IE browsers. We only support IE10 through Can I use

Let's Code

We'll start with the HTML structure, then the JavaScript, and then I'll give you 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:

<!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 bar display.

JavaScript

First, we need to get the tags we are going to use, they have been marked with id.

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, use to upload the file of our choice. 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 to process the upload, there are the following steps:

  1. Check the selected file

  2. Dynamicly create the file data to be sent

  3. Create XMLHttpRequest through js

  4. Upload file

Check the selected file

Our file input box _file has a query Select the file queue parameter files-if you set the multiple parameter, you can select multiple files. We do a simple check and judge. If the array length is greater than 0, continue, otherwise return directly.

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

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

var data = new FormData();
data.append(&#39;SelectedFile&#39;, _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 make sure the value is what we want - in this case it is 4, Represents the request completion.

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 wraps 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 properties that we are more concerned about. loaded and total.loaded represent the values ​​that have 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: There is no addition here Any animation effect, but you can customize the animation effect according to your needs.

Upload file

Now we can send the request, we will make a POST request to a file called upload .php file and use the send() method with the parameter data so that 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 to PHP.. .

PHP

This is the code we use, you will notice some differences, mainly that we use the top JSON method to return the values ​​as JSON format Output. This PHP is the same as the code in the previous article, which means that this method only applies 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;);

The above is me I compiled it for everyone, I hope it will be helpful to everyone in the future.

Related articles:

jQuery Validator verifies Ajax form submission method and Ajax parameter passing method (graphic tutorial)

Ajax asynchronous request technology example explanation

The principle of Ajax cross-domain request (picture and text tutorial)

The above is the detailed content of 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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!