Home  >  Article  >  Web Front-end  >  Implementing file upload with progress bar based on Ajax technology

Implementing file upload with progress bar based on Ajax technology

亚连
亚连Original
2018-05-23 17:00:291263browse

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

(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

(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 e388a4556c0f65e1904146cc1a846bee tag used to display the progress bar. and a 45a2772a6b6107b401db3c9b82c049c2 tag that displays the percentage. The key code is as follows:

Please select the uploaded file: bb421fb2602654b1d9b6d6045eb94537

Note: Please control the file size within 50M.

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

(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:



(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}

(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毫秒获取一次上传进度
}

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