java进行文件上传,带进度条

网上看到别人发过的一个java上传的代码,自己写了个完整的,附带源码

项目环境:jkd7、tomcat7、

jar包:commons-fileupload-1.2.1.jar、commons-io-1.4.jar

项目结构:

java进行文件上传,带进度条_第1张图片

 

 

index.jsp 代码

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML>
<html>
  <head>
    <base href="<%=basePath%>">
    <title>java进行文件上传,带进度条</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <script type="text/javascript" src="js/jquery-1.8.3.js"></script>
    <script type="text/javascript">
        var over = false;
        var inter;
        function upload(){
            over = false;
            $("#state").html("")
            $("#progress").css("width","0")
            $("input[type=submit]").attr("disabled",true);
            $("#progress").css("width","0%");
            $("#state").html("正在上传... 总大小:0MB,已上传:0MB,0%,已用时:0秒,剩余时间:0秒,速度:0KB/S");
            inter = setInterval(req,1000);
        }
        function req(){
            //如果上传已经完成
            if(over){
                clearInterval(inter);
                return;
            }
            var url = "upload/AjaxServlet";
            $.get(url,function(date){
                var state = date.split("-");
                $("#state").html("正在上传... 总大小:"+state[4]+"MB,已上传:"+state[3]+"MB,"+state[2]+"%,已用时:"+state[0]+"秒,剩余时间:"+state[5]+"秒,速度:"+state[1]+"KB/S");
                $("#progress").animate({width:state[2]+"%"},500);
                if(state[3] == state[4]){
                    over = true;
                    $("input[type=submit]").attr("disabled",false);
                    $("#state").html("上传已完成,总大小:"+state[4]+"MB,已上传:"+state[3]+"MB,"+state[2]+"%,已用时:"+state[0]+"秒,剩余时间:"+state[5]+"秒,速度:"+state[1]+"KB/S");
                }
            });    
        }
    </script>
  </head>
  
  <body>
      <form action="servlet/Upload" method="post" enctype="multipart/form-data" target="upload_iframe" onsubmit="upload()">
          <p><input type="file" name="file" id="file"></p>
          <p><input type="submit" value="上传文件"></p> 
      </form>
      <iframe name="upload_iframe" width="0" height="0" frameborder="0"></iframe>
      <div id="state">
      </div>
      <div id="progress" style="background: #728820; height: 10px; width: 0">
      </div>
  </body>
</html>
index.jsp

 

package com.sevennight.entity

 1 package com.sevennight.entity;
 2 
 3 public class Upload {
 4     private long totalSize;                                        //总大小
 5     private long startTime = System.currentTimeMillis();        //开始时间
 6     private long uploadSize;                                    //已上传的大小
 7     public long getTotalSize() {
 8         return totalSize;
 9     }
10     public void setTotalSize(long totalSize) {
11         this.totalSize = totalSize;
12     }
13     public long getStartTime() {
14         return startTime;
15     }
16     public void setStartTime(long startTime) {
17         this.startTime = startTime;
18     }
19     public long getUploadSize() {
20         return uploadSize;
21     }
22     public void setUploadSize(long uploadSize) {
23         this.uploadSize = uploadSize;
24     }
25 }
Upload.java

 

com.sevennight.lister

package com.sevennight.lister;

import org.apache.commons.fileupload.ProgressListener;

import com.sevennight.entity.Upload;

public class UploadLister implements ProgressListener{
    private Upload upload = null;
    
    public UploadLister(Upload upload){
        this.upload = upload;
    }
    
    public void update(long uploadSize,long totalSize,int items) {
        upload.setUploadSize(uploadSize);
        upload.setTotalSize(totalSize);
    }
}
UploadLister.java

 

com.sevennight.servlet

 1 package com.sevennight.servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 import com.sevennight.entity.Upload;
12 
13 @SuppressWarnings("serial")
14 public class AjaxServlet extends HttpServlet {
15 
16     public AjaxServlet() {
17         super();
18     }
19 
20     public void destroy() {
21         super.destroy(); // Just puts "destroy" string in log
22         // Put your code here
23     }
24 
25     public void doGet(HttpServletRequest request, HttpServletResponse response)
26             throws ServletException, IOException {
27         response.setHeader("Cache-Control", "no-store");// 禁止浏览器缓存
28         response.setHeader("Pragrma", "no-cache");// 禁止浏览器缓存
29         response.setDateHeader("Expires", 0);// 禁止浏览器缓存
30         response.setContentType("text/html");
31         PrintWriter out = response.getWriter();
32         Upload upload = null;
33         upload = (Upload)request.getSession().getAttribute("upload");
34         if(null == upload)
35             return;
36         long currentTime = System.currentTimeMillis();
37         //计算已用时,以S为单位
38         long time = (currentTime - upload.getStartTime()) / 1000 + 1;
39         //计算速度,以kb为单位
40         long speed = (long)(double)upload.getUploadSize() / 1024 / time;
41         //计算百分比
42         int percent =  (int)((double)upload.getUploadSize() / (double)upload.getTotalSize() * 100);
43         //已经完成
44         int mb = (int)upload.getUploadSize() / 1024 / 1024;
45         //总共有多少
46         int totalMb = (int)upload.getTotalSize() / 1024 / 1024;
47         //剩余时间
48         int shenYu =  (int)((upload.getTotalSize() - upload.getUploadSize()) / 1024 / speed);
49         String str = time+"-"+speed+"-"+percent+"-"+mb+"-"+totalMb+"-"+shenYu;
50         out.print(str);
51         out.flush();
52         out.close();
53     }
54 
55     public void doPost(HttpServletRequest request, HttpServletResponse response)
56             throws ServletException, IOException {
57 
58         response.setContentType("text/html");
59         PrintWriter out = response.getWriter();
60         out
61                 .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
62         out.println("<HTML>");
63         out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
64         out.println("  <BODY>");
65         out.print("    This is ");
66         out.print(this.getClass());
67         out.println(", using the POST method");
68         out.println("  </BODY>");
69         out.println("</HTML>");
70         out.flush();
71         out.close();
72     }
73 
74     public void init() throws ServletException {
75         // Put your code here
76     }
77 
78 }
AjaxServlet.java
  1 package com.sevennight.servlet;
  2 
  3 import java.io.File;
  4 import java.io.FileOutputStream;
  5 import java.io.IOException;
  6 import java.io.InputStream;
  7 import java.io.PrintWriter;
  8 import java.util.Iterator;
  9 import java.util.List;
 10 
 11 import javax.servlet.ServletException;
 12 import javax.servlet.http.HttpServlet;
 13 import javax.servlet.http.HttpServletRequest;
 14 import javax.servlet.http.HttpServletResponse;
 15 
 16 import org.apache.commons.fileupload.FileItem;
 17 import org.apache.commons.fileupload.FileUploadException;
 18 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
 19 import org.apache.commons.fileupload.servlet.ServletFileUpload;
 20 
 21 import com.sevennight.lister.UploadLister;
 22 
 23 @SuppressWarnings("serial")
 24 public class Upload extends HttpServlet {
 25 
 26     public Upload() {
 27         super();
 28     }
 29 
 30     public void destroy() {
 31         super.destroy(); 
 32     }
 33 
 34     public void doGet(HttpServletRequest request, HttpServletResponse response)
 35             throws ServletException, IOException {
 36 
 37         response.setContentType("text/html");
 38         PrintWriter out = response.getWriter();
 39         out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
 40         out.println("<HTML>");
 41         out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
 42         out.println("  <BODY>");
 43         out.print("    This is ");
 44         out.print(this.getClass());
 45         out.println(", using the GET method");
 46         out.println("  </BODY>");
 47         out.println("</HTML>");
 48         out.flush();
 49         out.close();
 50     }
 51 
 52     @SuppressWarnings({ "deprecation", "unchecked" })
 53     public void doPost(HttpServletRequest request, HttpServletResponse response)
 54             throws ServletException, IOException {
 55 
 56         response.setContentType("text/html");
 57         PrintWriter out = response.getWriter();
 58         
 59         com.sevennight.entity.Upload upload = new com.sevennight.entity.Upload();
 60         
 61         UploadLister lister = new UploadLister(upload);
 62         
 63         ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
 64         
 65         //只是上传监听器
 66         servletFileUpload.setProgressListener(lister);
 67         
 68         request.getSession().setAttribute("upload", upload);
 69         
 70         List list = null;
 71         try {
 72             list = servletFileUpload.parseRequest(request);
 73         } catch (FileUploadException e) {
 74             e.printStackTrace();
 75         }
 76         
 77         for(Iterator iter = list.iterator(); iter.hasNext();){
 78             //得到文件对象
 79             FileItem fileItem = (FileItem)iter.next();
 80             //是表单才进行处理
 81             if(fileItem.isFormField()){
 82                 break;
 83             }
 84             //同意linux和windows的路径分隔符
 85             String name = fileItem.getName().replaceAll("/", "\\");
 86             //得到文件名
 87             int index = name.lastIndexOf("\\");
 88             String fileFileName = "";
 89             if(index == -1){
 90                 fileFileName = name;
 91             }else{
 92                 fileFileName = name.substring(index + 1);
 93             }
 94             
 95             InputStream fileInputStream = fileItem.getInputStream();
 96             
 97             String path = request.getRealPath("/upload");
 98             System.out.println("上传路径:----->"+path);
 99             //也可不用自己写实现方法直接使用,fileItem.write(uploadFile);
100             File uploadFile = new File(path,fileFileName);
101             //首先要确认路径是否存在
102             uploadFile.getParentFile().mkdirs();
103             //检查文件是否已经存在
104             if(!uploadFile.exists()){
105                 //建立文件
106                 uploadFile.createNewFile();
107             }
108             FileOutputStream out2 = new FileOutputStream(uploadFile);
109             //开始copy文件
110             
111             @SuppressWarnings("unused")
112             int len = 0;//每次读取的字节数
113             byte[] bytes = new byte[1024]; 
114             while((len = fileInputStream.read(bytes, 0, bytes.length)) != -1){
115                 out2.write(bytes);
116             }
117             out2.flush();
118             out2.close();
119             fileInputStream.close();
120         }
121         out.flush();
122         out.close();
123     }
124 
125     public void init() throws ServletException {
126     }
127 
128 }
Upload.java

 

xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="2.5" 
 3     xmlns="http://java.sun.com/xml/ns/javaee" 
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 6     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 7     
 8   <servlet>
 9     <servlet-name>AjaxServlet</servlet-name>
10     <servlet-class>com.sevennight.servlet.AjaxServlet</servlet-class>
11   </servlet>
12   <servlet>
13     <servlet-name>Upload</servlet-name>
14     <servlet-class>com.sevennight.servlet.Upload</servlet-class>
15   </servlet>
16 
17 
18   <servlet-mapping>
19     <servlet-name>AjaxServlet</servlet-name>
20     <url-pattern>/upload/AjaxServlet</url-pattern>
21   </servlet-mapping>
22   <servlet-mapping>
23     <servlet-name>Upload</servlet-name>
24     <url-pattern>/servlet/Upload</url-pattern>
25   </servlet-mapping>
26   
27   <welcome-file-list>
28     <welcome-file>upload.jsp</welcome-file>
29   </welcome-file-list>
30 </web-app>
web.xml

 

源码地址http://pan.baidu.com/s/1i3JxC5v 

 

效果图:

java进行文件上传,带进度条_第2张图片

你可能感兴趣的:(java)