Example sharing Ajax upload file progress bar Codular
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='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 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('_submit'), _file = document.getElementById('_file'), _progress = document.getElementById('_progress');
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('click', upload);
Now we can continue processing the upload, there are the following steps:
Check the selected file
Dynamically create file data to be sent
Create XMLHttpRequest through js
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('SelectedFile', _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: 'error', data: 'Unknown error occurred: [' + request.responseText + ']' }; } console.log(resp.status + ': ' + 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('progress', function(e){ _progress.style.width = Math.ceil(e.loaded/e.total) * 100 + '%'; }, false);
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('POST', 'upload.php'); request.send(data);
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
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 = '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');
如果将所有内容都放在一起,您应该可以将文件上传到您期望的位置,并在浏览器的控制台内成功返回。
结束语
还有一些比较容易而又有效的方式来增强用户体验.通过将文件队列的多个文件加入到FormData,可以实现多文件上传. 有一点要说明,如果你是在本地做测试,你可能没办法看到进度条逐步变化,这取决于你本地机器的上传速度,我建议在服务器上使用较大的png文件做测试.
相关推荐:
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!

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Tmp format files are a temporary file format usually generated by a computer system or program during execution. The purpose of these files is to store temporary data to help the program run properly or improve performance. Once the program execution is completed or the computer is restarted, these tmp files are often no longer necessary. Therefore, for Tmp format files, they are essentially deletable. Moreover, deleting these tmp files can free up hard disk space and ensure the normal operation of the computer. However, before deleting Tmp format files, we need to

When deleting or decompressing a folder on your computer, sometimes a prompt dialog box "Error 0x80004005: Unspecified Error" will pop up. How should you solve this situation? There are actually many reasons why the error code 0x80004005 is prompted, but most of them are caused by viruses. We can re-register the dll to solve the problem. Below, the editor will explain to you the experience of handling the 0x80004005 error code. Some users are prompted with error code 0X80004005 when using their computers. The 0x80004005 error is mainly caused by the computer not correctly registering certain dynamic link library files, or by a firewall that does not allow HTTPS connections between the computer and the Internet. So how about

A file path is a string used by the operating system to identify and locate a file or folder. In file paths, there are two common symbols separating paths, namely forward slash (/) and backslash (). These two symbols have different uses and meanings in different operating systems. The forward slash (/) is a commonly used path separator in Unix and Linux systems. On these systems, file paths start from the root directory (/) and are separated by forward slashes between each directory. For example, the path /home/user/Docume

Quark Netdisk and Baidu Netdisk are currently the most commonly used Netdisk software for storing files. If you want to save the files in Quark Netdisk to Baidu Netdisk, how do you do it? In this issue, the editor has compiled the tutorial steps for transferring files from Quark Network Disk computer to Baidu Network Disk. Let’s take a look at how to operate it. How to save Quark network disk files to Baidu network disk? To transfer files from Quark Network Disk to Baidu Network Disk, you first need to download the required files from Quark Network Disk, then select the target folder in the Baidu Network Disk client and open it. Then, drag and drop the files downloaded from Quark Cloud Disk into the folder opened by the Baidu Cloud Disk client, or use the upload function to add the files to Baidu Cloud Disk. Make sure to check whether the file was successfully transferred in Baidu Cloud Disk after the upload is completed. That's it

Recently, many netizens have asked the editor, what is the file hiberfil.sys? Can hiberfil.sys take up a lot of C drive space and be deleted? The editor can tell you that the hiberfil.sys file can be deleted. Let’s take a look at the details below. hiberfil.sys is a hidden file in the Windows system and also a system hibernation file. It is usually stored in the root directory of the C drive, and its size is equivalent to the size of the system's installed memory. This file is used when the computer is hibernated and contains the memory data of the current system so that it can be quickly restored to the previous state during recovery. Since its size is equal to the memory capacity, it may take up a larger amount of hard drive space. hiber

1. Open Kugou Music and click on your profile picture. 2. Click the settings icon in the upper right corner. 3. Click [Upload Music Works]. 4. Click [Upload Works]. 5. Select the song and click [Next]. 6. Finally, click [Upload].

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

Detailed explanation of the role of .ibd files in MySQL and related precautions MySQL is a popular relational database management system, and the data in the database is stored in different files. Among them, the .ibd file is a data file in the InnoDB storage engine, used to store data and indexes in tables. This article will provide a detailed analysis of the role of the .ibd file in MySQL and provide relevant code examples to help readers better understand. 1. The role of .ibd files: storing data: .ibd files are InnoDB storage
