Ajax implements file upload with progress bar effect
This time I will bring you Ajax implementationFile uploadwith progress bar effect function, Ajax implementation of file upload with progress bar effectWhat are the precautions, the following is a practical case, Let’s take a look.
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 realize segmented file upload, so as to realize the upload process , and continuously obtain the upload progress. 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 the Common-FileUpload component implements file upload, you need to create a factory object and create a new one based on the factory object. File upload object, the specific code is as follows:
DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory);
(2) Parse upload request
After creating a file upload object, you can use the object to parse the upload request, Obtaining all form items 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, Treat it 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 Ajaxrequest method## in the file #.
(2) Create a new file upload page index.jsp, add a form and form elements for obtaining uploaded file information, and add a label and display percentage for displaying the progress bar. tag, the key code is as follows:
Note: Please control the file size within 50M. callback function to obtain the upload progress. The key code is as follows: window object is used to request the server at regular intervals to obtain the latest upload progress. The key code is as follows: How to use the parameters of the $.Ajax() method How to use ajax to add, delete, modify and check xml files The above is the detailed content of Ajax implements file upload with progress bar effect. For more information, please follow other related articles on the PHP Chinese website!<form enctype="multipart/form-data" method="post" action="UpLoad?action=uploadFile">
<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>
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);
}
}
<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>
<%@page contentType="text/html" pageEncoding="GBK"%>
${progressBar}
function deal(form){
form.submit(); //提交表单
timer=window.setInterval("getProgress()",500); //每隔500毫秒获取一次上传进度
}

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

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



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

With the advent of the digital age, music platforms have become one of the main ways for people to obtain music. However, sometimes when we listen to songs, we find that there are no lyrics, which is very disturbing. Many people hope that lyrics can be displayed when listening to songs to better understand the content and emotions of the songs. QQ Music, as one of the largest music platforms in China, also provides users with the function of uploading lyrics, so that users can better enjoy music and feel the connotation of the songs. The following will introduce how to upload lyrics on QQ Music. first

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

Upload speed becomes very slow? I believe this is a problem that many friends will encounter when uploading things on their computers. If the network is unstable when using a computer to transfer files, the upload speed will be very slow. So how can I increase the network upload speed? Below, the editor will tell you how to solve the problem of slow computer upload speed. When it comes to network speed, we all know that the speed of opening web pages, download speed, and upload speed are also very critical. Especially some users often need to upload files to the network disk, so a fast upload speed will undoubtedly save you a lot of money. Less time, what should I do if the upload speed is slow? Below, the editor brings you pictures and texts on how to deal with slow computer upload speeds. How to solve the problem of slow computer upload speed? Click "Start--Run" or "Window key"

As long as the computer is equipped with a camera, it can take pictures, but some users still don't know how to take pictures and upload them. Now I will give you a detailed introduction to the method of taking pictures on the computer, so that users can upload the pictures wherever they want. How to take photos and upload them on a computer 1. Mac computer 1. Open Finder and click the application on the left. 2. After opening, click the Camera application. 3. Just click the photo button below. 2. Windows computer 1. Open the search box below and enter camera. 2. Then open the searched application. 3. Click the photo button next to it.

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

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.
