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
2. Technical points
(1) Create an upload object
DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory);
(2) Parse the upload request
public List parseRequest(HttpServletRequest request) throws FileUploadException
(3) FileItem class
3. Specific implementation
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">
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>
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毫秒获取一次上传进度 }
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!