• 带有进度条监听事件的文件上传


    第一种方法:(利用jquery中自带的xhr属性)

    jsp页面代码:

     1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
     2 <html>
     3 <head>
     4     <title>文件上传监听</title>
     5 </head>
     6 <style>
     7     #box{
     8         width: 300px;
     9         height: 20px;
    10         border: 1px solid black;
    11     }
    12     #content{
    13         width: 0%;
    14         height: 20px;
    15         background: green;
    16         margin-top: -10px;
    17     }
    18 </style>
    19 <script src="js/jquery-1.11.3.min.js"></script>
    20 <body>
    21 <form id="frm" action="#" method="post">
    22     <p><input type="file" name="file" ></p>
    23     <p><input id="btn" type="button" value="提交"></p>
    24 </form>
    25 <p id="p"></p>
    26 <div id="box">
    27     <div id="content"></div>
    28 </div>
    29 
    30 </body>
    31 <script>
    32     $(function(){
    33         $("#btn").click(function(){
    34             var formData=new FormData($("#frm")[0]);
    35             $.ajax({
    36                 url:"listenerUpload.do",
    37                 type:"post",
    38                 data:formData,
    39                 dataType:"json",
    40                 contentType:false,
    41                 processData:false,
    42                 xhr:function(){
    43                     var myXhr=$.ajaxSettings.xhr();
    44                     if(myXhr.upload){
    45                         myXhr.upload.addEventListener("progress",function(event){
    46                             var loadedSize=event.loaded;
    47                             var loadSize=event.total;
    48                             var precent=Math.floor(100*(loadedSize/loadSize))+"%";
    49                             $("#content").css("width",precent);
    50                         },false);
    51                     }
    52                     return myXhr;
    53                 },
    54                 success:function(result){
    55                     if(result.data=="success"){
    56                         $("#p").text("上传成功!");
    57                     }else{
    58                         $("#p").text("上传失败!");
    59                     }
    60                 },
    61                 error:function(){
    62                     alert("服务器内部错误!");
    63                 }
    64             });
    65         });
    66 
    67     })
    68 </script>
    69 </html>

    servlet代码:

     1 package servlet;
     2 
     3 import com.alibaba.fastjson.JSONObject;
     4 import org.apache.commons.fileupload.FileItem;
     5 import org.apache.commons.fileupload.FileUploadException;
     6 import org.apache.commons.fileupload.ProgressListener;
     7 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
     8 import org.apache.commons.fileupload.servlet.ServletFileUpload;
     9 
    10 import javax.servlet.ServletException;
    11 import javax.servlet.annotation.WebServlet;
    12 import javax.servlet.http.HttpServlet;
    13 import javax.servlet.http.HttpServletRequest;
    14 import javax.servlet.http.HttpServletResponse;
    15 import java.io.File;
    16 import java.io.IOException;
    17 import java.io.PrintWriter;
    18 import java.util.List;
    19 import java.util.UUID;
    20 
    21 @WebServlet(value = "/listenerUpload.do")
    22 public class ListenerUploadServlet extends HttpServlet {
    23     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    24         PrintWriter out=response.getWriter();
    25         JSONObject jsonObject=new JSONObject();
    26         boolean flag=false;
    27         if(ServletFileUpload.isMultipartContent(request)){
    28             DiskFileItemFactory factory=new DiskFileItemFactory();
    29             factory.setSizeThreshold(1024000000);
    30             factory.setRepository(new File("D:\\res"));
    31             ServletFileUpload upload=new ServletFileUpload(factory);
    32             upload.setFileSizeMax(1024000000);
    33             upload.setSizeMax(1024000000);
    34             ProgressListener progressListener=new ProgressListener() {
    35                 @Override
    36                 public void update(long readByte, long totalByte, int i) {
    37                     System.out.println("已读字节:"+readByte+",总字节数:"+totalByte+",文件序号:"+i);
    38                 }
    39             };
    40             upload.setProgressListener(progressListener);
    41             try {
    42                 List<FileItem> fileItems=upload.parseRequest(request);
    43                 for(FileItem f:fileItems){
    44                     if(!f.isFormField()){
    45                         File file=new File("D:\\upload\\"+ UUID.randomUUID()+f.getName().substring(f.getName().lastIndexOf(".")));
    46                         f.write(file);
    47                         flag=true;
    48                     }else{
    49                         System.out.println("表单名:"+f.getFieldName()+" 输入值:"+f.getString("UTF-8"));
    50                     }
    51                 }
    52             } catch (FileUploadException e) {
    53                 e.printStackTrace();
    54             } catch (Exception e){
    55                 e.printStackTrace();
    56             }
    57         }
    58         if(flag){
    59             jsonObject.put("data","success");
    60         }else{
    61             jsonObject.put("data","error");
    62         }
    63         out.write(jsonObject.toString());
    64     }
    65 
    66     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    67         this.doPost(request,response);
    68     }
    69 }

    第二种方法:通过session存储文件上传进度

    jsp页面代码:

     1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
     2 <html>
     3 <head>
     4     <title>文件上传</title>
     5     <script src="js/jquery-1.11.3.min.js"></script>
     6     <script>
     7         //编写jQuery语句
     8         $(function () {
     9             var flag;
    10             $("[type=button]").click(function () {
    11                 var formDate=new FormData($("#frm")[0]);
    12                 $.ajax({
    13                     type:"post",
    14                     url:"UploadServlet",
    15                     data:formDate,
    16                     dataType:"json",
    17                     contentType:false,
    18                     processData:false,
    19                     success:function (result) {
    20                         flag=result.data;
    21                         /*if(result.data=="1" && $("#proInfo").text()=="上传进度:100%"){
    22                             alert("上传成功!")
    23                         }*/
    24                     },
    25                     error:function () {
    26                         alert("服务器内部错误!");
    27                     }
    28                 });
    29 
    30                 var pro=null;
    31                 pro=setInterval(function(){
    32                     $.get("UploadServlet","",function(data){
    33                         if(data=='100%'){
    34                             clearInterval(pro);
    35                             $("#proInfo").text("上传进度:100%");
    36                             //更新进度条
    37                             $("#progress").width("100%");
    38 
    39                             setTimeout(function () {
    40                                 if(flag=="1"){
    41 
    42                                     alert("上传成功!");
    43                                 }
    44                             },300);
    45 
    46 
    47                         }else{//正在上传
    48                             //更新进度信息
    49                             $("#proInfo").text("上传进度:"+data);
    50                             //更新进度条
    51                             $("#progress").width(data);
    52                         }
    53                     });
    54                 },200);
    55             });
    56 
    57 
    58         });
    59     </script>
    60     <style>
    61         #progressBar{width: 300px;height: 20px;border: 1px #EEE solid;}
    62         #progress{width: 0%;height: 20px;background-color: green;}
    63     </style>
    64 </head>
    65 <body>
    66 <form id="frm" method="post">
    67     <p><input type="file" name="ff"></p>
    68     <p>
    69         <input type="button" value="上传">
    70         <div id="progressBar">
    71             <div id="progress"></div>
    72         </div>
    73         <span id="proInfo">上传进度:0%</span>
    74     </p>
    75 </form>
    76 
    77 </body>
    78 </html>

    servlet代码:

     1 package servlet;
     2 
     3 
     4 import test.MyProgressListener;
     5 import net.sf.json.JSONObject;
     6 import org.apache.commons.fileupload.FileItem;
     7 import org.apache.commons.fileupload.FileUploadException;
     8 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
     9 import org.apache.commons.fileupload.servlet.ServletFileUpload;
    10 
    11 import javax.servlet.ServletException;
    12 import javax.servlet.annotation.WebServlet;
    13 import javax.servlet.http.HttpServlet;
    14 import javax.servlet.http.HttpServletRequest;
    15 import javax.servlet.http.HttpServletResponse;
    16 import java.io.File;
    17 import java.io.IOException;
    18 import java.io.PrintWriter;
    19 import java.util.List;
    20 import java.util.UUID;
    21 
    22 @WebServlet(value = "/UploadServlet")
    23 public class UploadServlet extends HttpServlet {
    24     @Override
    25     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    26         //取出监听器MyProgress在session中保存的进度信息
    27         String progress=(String) request.getSession().getAttribute("progress");
    28         //响应
    29         response.getWriter().print(progress);
    30         //清除session中保存的数据
    31        //request.getSession().removeAttribute("progress");
    32     }
    33 
    34     @Override
    35     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    36        response.setContentType("text/html");
    37         PrintWriter out = response.getWriter();
    38         JSONObject json=new JSONObject();
    39         /**
    40          * 1.判断请求是否为multipart
    41          * 2.创建磁盘工厂,设置内存大小和临时存储位置
    42          * 3.创建ServletFileUpload设置单个文件上传大小以及整个request域大小
    43          * 4.创建ProgressListener对象监听文件上传进度
    44          * 5.解析request域
    45          */
    46         int sign=0;
    47         //判断请求是否为multipart
    48         if(ServletFileUpload.isMultipartContent(request)){
    49             //创建磁盘工厂,设置内存大小和临时存储位置
    50             DiskFileItemFactory factory=new DiskFileItemFactory();
    51             //factory.setSizeThreshold(10240000);
    52             //如果文件大小大于内存大小则存储在临时存储空间
    53             factory.setRepository(new File("D:\\res"));
    54             //创建ServletFileUpload设置单个文件上传大小以及整个request域大小
    55             ServletFileUpload upload=new ServletFileUpload(factory);
    56             //upload.setFileSizeMax(10240000);
    57             //upload.setSizeMax(10240000);
    58             //创建ProgressListener对象监听文件上传进度
    59             upload.setProgressListener(new MyProgressListener(request));
    60 
    61             //解析request域
    62             try {
    63                 List<FileItem> fileItems=upload.parseRequest(request);
    64                 for (FileItem f:fileItems){
    65                     if(!f.isFormField()){//判断是否是普通表单域,如果是普通表单域则解析不了
    66                         File file=new File("D:\\upload\\"+ UUID.randomUUID()+f.getName().substring(f.getName().lastIndexOf(".")));
    67                         f.write(file);
    68                         sign++;
    69                         json.put("data",sign);
    70                     }else {
    71                         System.out.println("表单名:"+f.getFieldName()+"    输入值:"+f.getString("UTF-8"));
    72                     }
    73                 }
    74             } catch (FileUploadException e) {
    75                 e.printStackTrace();
    76             } catch (Exception e){
    77                 e.printStackTrace();
    78             }
    79         }
    80         out.write(json.toString());
    81 
    82 }
    83 }

    监听器MyProgressListener类代码:

     1 package test;
     2 
     3 import org.apache.commons.fileupload.ProgressListener;
     4 
     5 import javax.servlet.http.HttpServletRequest;
     6 import javax.servlet.http.HttpSession;
     7 import java.text.NumberFormat;
     8 
     9 
    10 public class MyProgressListener implements ProgressListener {
    11 
    12     private HttpSession session;
    13     public MyProgressListener(HttpServletRequest request){
    14         session = request.getSession();
    15     }
    16 
    17     @Override
    18     public void update(long pBytesRead, long pContentLength, int pItems) {
    19         //将数据进行格式化
    20         //已读取数据由字节转换为M
    21         double readM=pBytesRead/1024.0/1024.0;
    22         //已读取数据由字节转换为M
    23         double totalM=pContentLength/1024.0/1024.0;
    24         //已读取百分百
    25         double percent=readM/totalM;
    26 
    27         //格式化数据
    28         //已读取
    29         String readf=dataFormat(pBytesRead);
    30         //总大小
    31         String totalf=dataFormat(pContentLength);
    32         //进度百分百
    33         NumberFormat format=NumberFormat.getPercentInstance();
    34         String progress=format.format(percent);
    35 
    36         //将信息存入session
    37         session.setAttribute("progress", progress);
    38 
    39         //打印消息到控制台
    40         System.out.println("pBytesRead===>"+pBytesRead);
    41         System.out.println("pContentLength==>"+pContentLength);
    42         System.out.println("pItems===>"+pItems);
    43         System.out.println("readf--->"+readf);
    44         System.out.println("totalf--->"+totalf);
    45         System.out.println("progress--->"+progress);
    46     }
    47 
    48     /**
    49      * 格式化读取数据的显示
    50      * @param data 要格式化的数据 单位byte
    51      * @return 格式化后的数据,如果小于1M显示单位为KB,如果大于1M显示单位为M
    52      */
    53     public String dataFormat(double data){
    54         String formdata="";
    55         if (data>=1024*1024) {//大于等于1M
    56             formdata=Double.toString(data/1024/1024)+"M";
    57         }else if(data>=1024){//大于等于1KB
    58             formdata=Double.toString(data/1024)+"KB";
    59         }else{//小于1KB
    60             formdata=Double.toString(data)+"byte";
    61         }
    62         return formdata.substring(0, formdata.indexOf(".")+2);
    63     }
    64 }
  • 相关阅读:
    数据库——Oracle(7)
    数据库——Oracle(6)
    数据库——Oracle(5)
    数据库——Oracle(4)
    数据库——Oracle(3)
    数据库——Oracle(2)
    Java 学习笔记之 Synchronized锁对象
    Java 学习笔记之 线程安全
    Java 学习笔记之 实例变量非线程安全
    Java 学习笔记之 方法内的临时变量是线程安全
  • 原文地址:https://www.cnblogs.com/leafarmyarmy/p/10431501.html
Copyright © 2020-2023  润新知