Home Web Front-end JS Tutorial Implementing file upload with progress bar based on Ajax technology

Implementing file upload with progress bar based on Ajax technology

May 23, 2018 pm 05:00 PM
ajax accomplish document

This article mainly introduces the relevant information on implementing file upload with progress bar based on Ajax technology. It is very good and has reference value. Friends in need can refer to

##1. Overview

In the actual web application development or website development process, it is often necessary to implement the file upload function. During the file upload process, users often need to wait for a long time. In order to let users know the upload progress in time, the file upload progress bar can be displayed while uploading the file. Run this example, as shown in Figure 1, access the file upload page, click the "Browse" button to select the file to be uploaded, note that the file cannot exceed 50MB, otherwise the system will give an error prompt. After selecting the file to be uploaded, click the "Submit" button, the file will be uploaded and the upload progress will be displayed.


2. Technical points

Mainly uses the open source Common-FileUpload component to achieve segmented file upload. In this way, the upload progress can be continuously obtained during the upload process. The Common-FileUpload component is introduced in detail below.


The Common-FileUpload component is a sub-project under the jakarta-commons project under the Apache organization. This component can easily parse various form fields in multipart/form-data type requests. This component requires support from another component called Common-IO. These two component package files can be downloaded from the http://commons.apache.org website.


(1) Create an upload object

#When implementing file upload using the Common-FileUpload component, a factory object needs to be created and based on the The factory object creates a new file upload object. The specific code is as follows:


DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
Copy after login

(2) Parse the upload request

After creating a file upload object, you can use the object to parse the upload request and obtain all form items. This can be achieved through the parseRequest() method of the file upload object. The syntax structure of the parseRequest() method is as follows:


public List parseRequest(HttpServletRequest request) throws FileUploadException
Copy after login

(3) FileItem class

In the Common-FileUpload component, whether it is a file field or a normal form field, it is treated as a FileItem object. If the object's isFormField() method returns true, it means it is an ordinary form field, otherwise it is a file field. When implementing file upload, you can obtain the file name of the uploaded file through the getName() method of the FileItem class, and obtain the size of the uploaded file through the getSize() method.


3. Specific implementation

(1) Create the request.js file and write the Ajax request in the file method.


(2) Create a new file upload page index.jsp, add the form and form elements used to obtain uploaded file information, and add the

tag used to display the progress bar. and a tag that displays the percentage. The key code is as follows:

<form enctype="multipart/form-data" method="post" action="UpLoad?action=uploadFile">
Copy after login

Please select the uploaded file:

Note: Please control the file size within 50M.

<p id="progressBar" class="prog_border" align="left">
<img src="images/progressBar.gif" width="0" height="13" id="imgProgress"></p>
<span id="progressPercent" style="width:40px;display:none">0%</span>
<input name="Submit" type="button" value="提交" onClick="deal(this.form)">
<input name="Reset" type="reset" class="btn_grey" value="重置"></td>
</form>
Copy after login

(3) Create a new Servlet implementation class UpLpad for uploading files. Write the method uploadFile() in this class to implement file upload. In this method, the Common-FileUpload component is used to upload files in sections, calculate the upload percentage, and save it to the Session in real time. The key code is as follows:


public void uploadFile(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=GBK");
request.setCharacterEncoding("GBK");
HttpSession session=request.getSession();
session.setAttribute("progressBar",0); //定义指定上传进度的Session变量
String error = "";
int maxSize=50*1024*1024; //单个上传文件大小的上限
DiskFileItemFactory factory = new DiskFileItemFactory(); //创建工厂对象
ServletFileUpload upload = new ServletFileUpload(factory); //创建一个新的文件上传对象
try {
List items = upload.parseRequest(request); // 解析上传请求
Iterator itr = items.iterator(); // 枚举方法
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next(); //获取FileItem对象
if (!item.isFormField()) { // 判断是否为文件域
if (item.getName() != null && !item.getName().equals("")) {//是否选择了文件
long upFileSize=item.getSize(); //上传文件的大小
String fileName=item.getName(); //获取文件名
if(upFileSize>maxSize){
error="您上传的文件太大,请选择不超过50M的文件";
break;
}
// 此时文件暂存在服务器的内存中
File tempFile = new File(fileName); //构造文件目录临时对象
String uploadPath = this.getServletContext().getRealPath("/upload");
File file = new File(uploadPath,tempFile.getName()); 
InputStream is=item.getInputStream();
int buffer=1024; //定义缓冲区的大小
int length=0;
byte[] b=new byte[buffer];
double percent=0;
FileOutputStream fos=new FileOutputStream(file);
while((length=is.read(b))!=-1){
percent+=length/(double)upFileSize*100D; //计算上传文件的百分比
fos.write(b,0,length); //向文件输出流写读取的数据
session.setAttribute("progressBar",Math.round(percent)); 
}
fos.close();
Thread.sleep(1000); //线程休眠1秒
} else {
error="没有选择上传文件!";
}
}
}
} catch (Exception e) {
e.printStackTrace();
error = "上传文件出现错误:" + e.getMessage();
}
if (!"".equals(error)) {
request.setAttribute("error", error);
request.getRequestDispatcher("error.jsp").forward(request, response);
}else {
request.setAttribute("result", "文件上传成功!");
request.getRequestDispatcher("upFile_deal.jsp").forward(request, response);
}
}
Copy after login

(4) In the file upload page index.jsp, import the request.js file of the Ajax request method written, and write the Ajax request method to obtain the upload progress and Ajax callback function, the key code is as follows:


<script language="javascript" src="js/request.js"></script>
<script language="javascript">
var request = false;
function getProgress(){ 
var url="showProgress.jsp"; //服务器地址
var param ="nocache="+new Date().getTime(); //每次请求URL参数都不同 ,避免上传时进度条不动
request=httpRequest("post",url,true,callbackFunc,param); //调用请求方法 
}
//Ajax回调函数
function callbackFunc(){
if( request.readyState==4 ){ //判断响应是否完成 
if( request.status == 200 ){ //判断响应是否成功
var h = request.responseText; //获得返回的响应数据,该数据位上传进度百分比
h=h.replace(/\s/g,""); //去除字符串中的Unicode空白符
document.getElementById("progressPercent").style.display=""; //显示百分比 
progressPercent.innerHTML=h+"%"; //显示完成的百分比
document.getElementById("progressBar").style.display="block"; //显示进度条
document.getElementById("imgProgress").width=h*(235/100); //显示完成的进度
}
}
}
</script>
Copy after login

(5) Write the showProgress.jsp page, apply the EL expression in this page and save the output in The value of the upload progress bar in the session domain, the specific code is as follows:


<%@page contentType="text/html" pageEncoding="GBK"%>
${progressBar}
Copy after login

(6) Write the JavaScript method called by the form submit button onclick event , in this method, the server is requested at regular intervals through the setInterval() method of the window object to obtain the latest upload progress. The key code is as follows:


function deal(form){
form.submit(); //提交表单
timer=window.setInterval("getProgress()",500); //每隔500毫秒获取一次上传进度
}
Copy after login

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

Related articles:

Discuss issues related to readyState and status in Ajax

Comprehensive analysis of the $.Ajax() method Parameters (graphic tutorial)

Ajax caching problems and solutions under IE8

The above is the detailed content of Implementing file upload with progress bar based on Ajax technology. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What to do if the 0x80004005 error code appears. The editor will teach you how to solve the 0x80004005 error code. What to do if the 0x80004005 error code appears. The editor will teach you how to solve the 0x80004005 error code. Mar 21, 2024 pm 09:17 PM

When deleting or decompressing a folder on your computer, sometimes a prompt dialog box &quot;Error 0x80004005: Unspecified Error&quot; 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

How to transfer files from Quark Cloud Disk to Baidu Cloud Disk? How to transfer files from Quark Cloud Disk to Baidu Cloud Disk? Mar 14, 2024 pm 02:07 PM

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

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

What is hiberfil.sys file? Can hiberfil.sys be deleted? What is hiberfil.sys file? Can hiberfil.sys be deleted? Mar 15, 2024 am 09:49 AM

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

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

Detailed explanation of the role of .ibd files in MySQL and related precautions Detailed explanation of the role of .ibd files in MySQL and related precautions Mar 15, 2024 am 08:00 AM

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

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

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.

See all articles