java 实现异步批量上传文件,带进度条方法

ps:java 实现批量上传文件的方法,使用前端组件 uploadify,可以实现异步带进度条上传 。废话不多说,下面给出实现方法及代码。


1,首先下载 uploadify 组件,然后引用到项目中。下载地址:http://moxcn.qiniudn.com/uploadify.zip

2,实现一个上传文件servlet类 UploadFileServlet:

java代码:


?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package com.wecwdf.servlet;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
import com.wecwdf.entity.BookEntity;
import com.wecwdf.service.BookService;
import com.wecwdf.util.Escape;
 
/**
 * Servlet implementation class UploadFileServlet
 */
public class UploadFileServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    Logger logger = Logger.getLogger(getClass());
    ClassPathXmlApplicationContext context;
    BookService bookService;
     
    @Override
    public void init() throws ServletException {
        context = new ClassPathXmlApplicationContext("classpath:spring_config/applicationContext.xml");
        //JdbcContextHolder.setMaster();
        bookService = (BookService)context.getBean("bookService");
         
        super.init();
    }
        
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadFileServlet() {
        super();
    }
 
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        upload(request, response);
    }
 
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
     
    String PATH = "/tmp/";
    public void upload(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {     
        String bookType = request.getParameter("bookType");
        logger.info("upload start!,bookTypeId:"+bookType);
         
        String[] strs = bookType.split(",");
        int bookTypeId = Integer.valueOf(strs[0]);
        String typeName = Escape.binaryToUnicode(strs[1]);     
         
        BookEntity be = new BookEntity(request);
        be.setBookTypeId(Integer.valueOf(bookTypeId));
        be.setTypeName(typeName);
         
        String savePath = this.getServletConfig().getServletContext().getRealPath("");
        savePath = savePath + PATH;
        File f1 = new File(savePath);
         
        if (!f1.exists()) {
            f1.mkdirs();
        }
     
        DiskFileItemFactory fac = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setHeaderEncoding("utf-8");
        List fileList = null;
        try {
            fileList = upload.parseRequest(request);
        } catch (FileUploadException ex) {
            logger.error("FileUploadException",ex);
            return;
        }
        Iterator<FileItem> it = fileList.iterator();
        String name = "";
        while (it.hasNext()) {
            FileItem item = it.next();
            if (!item.isFormField()) {
                name = item.getName();
                logger.info("===name:"+name);
                 
                long size = item.getSize();
                String type = item.getContentType();
                 
                if (!StringUtils.isEmpty(name)) {
                    if (name.endsWith(".txt")
                            || name.endsWith(".TXT")) {
                        File saveFile = new File(savePath + name );
                        try {
                            item.write(saveFile);
                            logger.info("===item.write success!  saveFile:"+saveFile);
                        } catch (Exception e) {
                            logger.error("Exception",e);
                        }
                        be.setBookFis(new FileInputStream(saveFile));
                        be.setFileName(saveFile.getName());
                        be.setPopularity(9);
                        bookService.saveBook(be);
                        logger.info(be.getFileName());
                    }
                }      
                 
            }
        }
        logger.info("upload end!  fileName:"+be.getFileName());
        response.getWriter().print(name );
    }
 
}


3,配置web.xml 


?
1
2
3
4
5
6
7
8
9
10
<servlet>
    <description></description>
    <display-name>UploadFileServlet</display-name>
    <servlet-name>UploadFileServlet</servlet-name>
    <servlet-class>com.wecwdf.servlet.UploadFileServlet</servlet-class>
  </servlet>
<servlet-mapping>
    <servlet-name>UploadFileServlet</servlet-name>
    <url-pattern>/UploadFileServlet</url-pattern>
  </servlet-mapping>


4,然后实现前端上传文件jsp  fileUpload.jsp


?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>The FileUpload Demo</title>
<link href="<%=basePath%>uploadify/uploadify.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="<%=basePath%>uploadify/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="<%=basePath%>uploadify/swfobject.js"></script>
<script type="text/javascript" src="<%=basePath%>uploadify/jquery.uploadify.v2.1.4.min.js"></script>
</head>
 
<body>
    <form action="${pageContext.request.contextPath}/admin/fileUpload.do"
        method="post" enctype="multipart/form-data">
        <table width="100%" border="0" cellspacing="0" cellpadding="0">
            <tr>
                <td height="30" align="right">Choose File</td>
                <td align="left">img<input name="imageFile" type="file" /></td>
                <td align="left">txt<input name="txtFile" type="file" /></td>
            </tr>
            <tr>
            <div id="fileQueue"></div>
    <input type="file" name="uploadify" id="uploadify" />
    <p>
         <a href="javascript: jQuery('#uploadify').uploadifyUpload()">开始上传</a>&nbsp;
        <a href="javascript:jQuery('#uploadify').uploadifyClearQueue()">取消所有上传</a>
    </p>
            </tr>
            <tr>
                <td align="center" colspan="3"><input type="submit"
                    value="submit" name="submit" /></td>
            </tr>
        </table>
    </form>
 
</body>
<script type="text/javascript">
//官方网址:http://www.uploadify.com/
$(document).ready(function(){
    //$("#uploadify").uploadifySettings('scriptData',   {'name':'liudong','age':22});
    $("#uploadify").uploadify({
        'uploader'  :   "<%=basePath%>uploadify/uploadify.swf",
        'script'    :   "<%=basePath%>/UploadFileServlet",
        'cancelImg' :   "<%=basePath%>uploadify/cancel.png",
        'folder'    :   "uploads",//上传文件存放的路径,请保持与uploadFile.jsp中PATH的值相同
        'queueId'   :   "fileQueue",
        'queueSizeLimit'    :   20,//限制上传文件的数量
        'fileExt'   :   "*.rar,*.zip",
        //'fileDesc'    :   "RAR *.rar",//限制文件类型
        'auto'      :   false,
        'multi'     :   true,//是否允许多文件上传
        'simUploadLimit':   1,//同时运行上传的进程数量
        'buttonText':   "files",
        'scriptData':   {'name':'liudong','age':22},//这个参数用于传递用户自己的参数,此时'method' 必须设置为GET, 后台可以用request.getParameter('name')获取名字的值
        'method'    :   "GET"
    });
     
    //$("#uploadify").uploadifySettings();
});
</script>
</html>


5,ok,到这里就基本完成了,简单吧,接下来就可以运行项目看上传效果了。


本博客所有文章如无特别注明均为原创。作者:封笔尘缘复制或转载请以超链接形式注明转自 封笔尘缘
原文地址《java 实现异步批量上传文件,带进度条方法
分享到:更多

相关推荐

网友评论(2)

博主你好 我是咱java群的 你这个博客做的还是不够精致啊 上面那个源码进度条怎么跨越这么大 一开始我还以为是浏览器不对呢..
小菜 5年前 (2014-09-26) 回复
@小菜:由于刚换了模板 很多东西都不适应 以后我会改的
Admin 5年前 (2014-09-26) 回复