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='container'> <p> Select File: <input type='file' id='_file'> <input type='button' id='_submit' value='Upload!'> </p> <p class='progress_outer'> <p id='_progress' class='progress'></p> </p> </p> <script src='upload.js'></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('_submit'), _file = document.getElementById('_file'), _progress = document.getElementById('_progress');
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('click', upload);
Now we can continue to process the upload, there are the following steps:
Check the selected file
Dynamicly create the file data to be sent
Create XMLHttpRequest through js
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('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 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: 'error', data: 'Unknown error occurred: [' + request.responseText + ']' }; } console.log(resp.status + ': ' + 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('progress', function(e){ _progress.style.width = Math.ceil(e.loaded/e.total) * 100 + '%'; }, 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('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) * 100 + '%'; }, false); request.open('POST', 'upload.php'); request.send(data); } _submit.addEventListener('click', 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 = 'error'){ header('Content-Type: application/json'); die(json_encode(array( 'data' => $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');
The above is me I compiled it for everyone, I hope it will be helpful to everyone in the future.
Related articles:
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!

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

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version

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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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.