利用apache的Commons-fileupload和Ajax實現檔案上傳進度條__Ajax

來源:互聯網
上載者:User

實現思路:

1、首先自訂一個進度堅挺實作類別ProgressListener介面,重寫upload方法。

2、通過以讀取的位元組數跟檔案總的位元組數產生百分比,將值放到session中

3、建立一個servlet用來擷取session中的百分比

4、在上傳檔案介面,在表單提交時,Ajax每個100毫秒訪問第三步中建立的servlet響應的百分比值,顯示在介面。

參考代碼:

自訂監聽類實現ProgressListener

package cn.progressBar;import java.text.NumberFormat;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;import org.apache.commons.fileupload.ProgressListener;/** * 自訂監聽類實現ProgressListener * @author l * *///@WebListenerpublic class MyProgressListener implements ProgressListener{private double megaBytes = -1;private HttpSession session;public MyProgressListener(){}public MyProgressListener(HttpServletRequest request){session = request.getSession();}@Overridepublic void update(long pBytesRead, long pContentLength, int pItems) {// TODO Auto-generated method stubdouble mBytes = pBytesRead / (1024*1024);  //pBytesRead到目前為止讀取檔案的位元數        double total=pContentLength/(1024*1024);  //pContentLength 檔案總大小           if (megaBytes == mBytes) {                 return;             }             System.out.println("檔案總大小:"+total+"M");             System.out.println("已讀取:"+mBytes+"M");             megaBytes = mBytes;             System.out.println("目前正在讀取第幾個檔案 " + pItems);  //pItems目前正在讀取第幾個檔案           if (pContentLength == -1) {                 System.out.println("So far, " + pBytesRead + " bytes have been read.");             } else {                 System.out.println("So far, " + pBytesRead + " of " + pContentLength                                    + " bytes have been read.");                double read=(mBytes/total);                NumberFormat nf=NumberFormat.getPercentInstance();                System.out.println("read===>"+nf.format(read));//產生讀取的百分比 並放入session中                session.setAttribute("read", nf.format(read));             }  }}
封裝FileUpload 用來接收request中的表單域 和 file檔案域
package cn.progressBar;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import javax.servlet.http.HttpServletRequest;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.FileItemFactory;import org.apache.commons.fileupload.FileUploadException;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;public class FileUpload {      private Map<String,String> params;      private Map<String,FileItem> files;            public FileUpload() {          params=new HashMap<String, String>();          files=new HashMap<String, FileItem>();      }        @SuppressWarnings("rawtypes")public void setMap(HttpServletRequest request){          // Create a factory for disk-based file items          FileItemFactory factory = new DiskFileItemFactory();          // Create a new file upload handler          ServletFileUpload upload = new ServletFileUpload(factory);          upload.setHeaderEncoding("utf-8");          upload.setProgressListener(new MyProgressListener(request));//設定進度監聽器          // Parse the request          try {              List items = upload.parseRequest(request);              Iterator iter = items.iterator();              while (iter.hasNext()) {                  FileItem item = (FileItem) iter.next();                  if (item.isFormField()) {                      String name = item.getFieldName();                      String value = item.getString();                      params.put(name, value);                  }                   else{                      String name=item.getFieldName();                      files.put(name, item);                  }              }          } catch (FileUploadException e) {              e.printStackTrace();          }      }        public Map<String, String> getParams() {          return params;      }        public Map<String, FileItem> getFiles() {          return files;      }      //用來擷取檔案的名字      public String getFileName(FileItem item){          String fName=item.getName();          System.out.println("fname=====>"+fName);          int lastIndex=fName.lastIndexOf("\\");          fName=fName.substring(lastIndex+1);          System.out.println("new fname=====>"+fName);          return fName;      }  }  
實現上傳檔案servlet

package cn.progressBar;import java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.util.Map;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.FileItem;@WebServlet("/FileUploadServlet")public class FileUploadServlet extends HttpServlet {       protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {         doPost(request, response);}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType("text/html;charset=utf-8");          PrintWriter out = response.getWriter();          FileUpload fu=new FileUpload();          fu.setMap(request);//解析request          Map<String,FileItem> files=fu.getFiles();          String fileName =fu.getFileName(files.get("file"));          File file=new File(this.getServletContext().getRealPath("upload\\"+fileName));          try {                            files.get("file").write(file);                        } catch (Exception e) {              e.printStackTrace();          }          out.println("<script>alert('上傳成功。');history.go(-1);</script>");}}
實現用來響應上傳進度的servlet FileUploadStatus

package cn.progressBar;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;@WebServlet("/FileUploadStatus")public class FileUploadStatus extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    doPost(request, response);}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("--------------------------------------------------------------------------------------------------------------------------");response.setContentType("text/html;charset=utf-8");          PrintWriter out = response.getWriter();          HttpSession session=request.getSession();                    String status=(String) session.getAttribute("read");//擷取上傳進度百分比          System.out.println(status+"FileUploadStatus");          out.println(status);//響應}}
index.jsp 完整內容

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><script type="text/javascript" src="js/jquery-1.11.0.js"></script><script type="text/javascript">function callback() {//alert("=======");//alert("*********************");$.ajax({//http://localhost:8080/progressBar/index.jsptype : "POST",url : "FileUploadStatus",//回應檔上傳進度的servlet  FileUploadStatussuccess : function(msg) {//document.getElementById("span").innerHTML = msg;//顯示讀取百分比  已上傳//document.getElementById("table").width = msg;//通過表格寬度 實現進度條var bl = parseInt(msg);//alert(bl); if(bl<20 && bl >=0){ $("#show").html("<div style='width:"+msg+";background-color: #f90;border-radius:8px;text-align:right'>"+msg+"</div>");} if(bl<40 && bl >=20){$("#show").html("<div style='width:"+msg+";background-color: #c90;border-radius:8px;text-align:right'>"+msg+"</div>");}if(bl<60 && bl >=40){$("#show").html("<div style='width:"+msg+";background-color: #990;border-radius:8px;text-align:right'>"+msg+"</div>");}if(bl<75 && bl >=60){$("#show").html("<div style='width:"+msg+";background-color: #690;border-radius:8px;text-align:right'>"+msg+"</div>");}if(bl<90 && bl >=75){$("#show").html("<div style='width:"+msg+";background-color: #390;border-radius:8px;text-align:right'>"+msg+"</div>");}if(bl<=100 && bl >=90){$("#show").html("<div style='width:"+msg+";background-color: #090;border-radius:8px;text-align:right'>"+msg+"</div>");} //$("#show").html("<div style='width:"+msg+";background-color: orange;border-radius:8px;text-align:right'>"+msg+"</div>");}});}function formSubmit(){        window.setInterval("callback()", 10);//每隔100毫秒執行          document.form.submit();    } </script></head><body><form action="FileUploadServlet" method="post"enctype="multipart/form-data" target="_parent" name="form"><input type="file" name="file" ><input type="button" onclick="formSubmit()" value="提交"></form><!-- <span id="span"></span> --><!-- <table width="300px;" border="0"><tr><td><table id="table" height="30px" style="background-color: gray;"><tr><td align="right"><span id="span"></span></td></tr></table>實現進度條的顯示</td></tr></table> --><div style="width:300px;border-radius:8px;" id="show">   </div></body></html>

效果圖:

註:不要忘了引用jquery


參考:http://blog.csdn.net/hxlzpnyist/article/details/7601611


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.