java+uploadify+springmvc实现多文件上传

需求:实现多文件上传。

实现方式 uploadify +springmvc

controller

fileUrl:文件存放的位置。我放在tomcat下的一个文件夹中

@ResponseBody
    @RequestMapping("/fileUpload")
    public String fileUpload(@RequestParam MultipartFile[] attachment, HttpServletRequest request) {
        String uuid = request.getParameter("uuid");
        String returnStr = "";
        
        String fileUrl = System.getProperty("catalina.home") + File.separator + Global.VOUCHER_FILE_PATH;
        
        File dir=new File(fileUrl);
        if(!dir.exists()){//如果文件夹不存在
            dir.mkdir();//创建文件夹
        }
        List<Attachment> attachments = new ArrayList<>();
        if (null != attachment) {
            for (MultipartFile file : attachment) {
                if (!file.isEmpty()) {
                    // 文件保存操作
                    String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
                    String path = fileUrl + File.separator + fileName;
                    File localFile = new File(path);
                    try {
                        file.transferTo(localFile);
                    } catch (IllegalStateException e) {
                        returnStr = e.getMessage();
                        e.printStackTrace();
                    } catch (IOException e) {
                        returnStr = e.getMessage();
                        e.printStackTrace();
                    }
                    // 数据库新增记录
                    Attachment att = new Attachment();
                    String id = UUID.randomUUID().toString();
                    att.setId(id);
                    att.setAsocciateId(uuid);
                    att.setAttachmentType(Attachment.AttachmentType.VOUCHER);
                    att.setFileName(fileName);
                    att.setFileUrl(fileUrl);
                    attachments.add(att);

                }
            }
        }

        try {
            attachmentService.fileUploadBatch(attachments);
            returnStr = "文件上传成功!";
        } catch (Exception e) {
            System.out.println(e.getMessage());
            returnStr = "文件上传失败!" + e.getMessage();
            e.printStackTrace();
        }
        return returnStr;
    }

jsp代码如下

  一切看注释,拓展操作参考uploadify API 

 

<%@ 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>凭证录入</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<base href="<%=basePath%>">
<link rel="stylesheet"
    href="<%=path%>/resources/style/record-background.css" type="text/css" />
<!-- 通用的文件导入 -->
<jsp:include page="/base.jsp"></jsp:include>
<script type="text/javascript"
    src="<%=path%>/resources/script/extjs4.2/ux/ComBoTree.js"></script>
<script type="text/javascript"
    src="<%=path%>/resources/ueditor/third-party/jquery-1.10.2.min.js"></script>
<script>
    var month = "${requestScope.month}";
</script>
<script src="<%=path%>/resources/script/LoDop/LodopFuncs.js"></script>
<script
    src="<%=path%>/resources/script/uploadify/jquery.uploadify.min.js"></script>
<link rel="stylesheet" type="text/css"
    href="<%=path%>/resources/script/uploadify/uploadify.css">
<style type="text/css">
body {
    font: 13px Arial, Helvetica, Sans-serif;
}
</style>
<script type="text/javascript">
     
    var ids = "";
    var names = "";
    var type = "";
    var isComplete=true;
        $(function() {
            var jsid= $("#JSESSIONID").val();
            var uuid= $("#uuid").val();
            var sid=$("#msm_ticket_sessionID").val();
            $("#uploadify").uploadify({
                auto:false,
                debug            : false, 
                langFile        : '<%=path%>/resources/script/uploadify/lang_zn.js',
                swf             : '<%=path%>/resources/script/uploadify/uploadify.swf',    
                method            : 'post',    // 提交方式
                uploader        : 'fileUpload', // 服务器端处理该上传请求的程序(servlet, struts2-Action)
                preventCaching    : true,        // 加随机数到URL后,防止缓存
                buttonCursor    : 'hand',    // 上传按钮Hover时的鼠标形状
                //buttonImage        : 'img/.....png',    // 按钮的背景图片,会覆盖文字
                buttonText        : '请选择文件'    , //按钮上显示的文字,默认”SELECTFILES”
                height            : 30    , // 30 px
                width            : 120    , // 120 px
                fileObjName        : 'attachment',    //文件对象名称, 即属性名
                fileSizeLimit    : 10240,        // 文件大小限制, 100 KB
                fileTypeDesc    : 'any'    ,    //文件类型说明 any(*.*)
                fileTypeExts    : '*.*',//'*.doc;*.txt;*.docx',        // 允许的文件类型,分号分隔
                formData        : {'JSESSIONID':jsid,'msm_ticket_sessionID':sid,'uuid':uuid} , //指定上传文件附带的其他数据。也动态设置。可通过getParameter()获取
                multi            : true ,    // 多文件上传
                progressData    : 'percentage',    // 进度显示, speed-上传速度,percentage-百分比    
                queueID            : 'fileQueue',//上传队列的DOM元素的ID号
                queueSizeLimit    : 99    ,    // 队列长度
                removeCompleted : false    ,    // 上传完成后是否删除队列中的对应元素
                removeTimeout    : 10    ,    //上传完成后多少秒后删除队列中的进度条, 
                requeueErrors    : true,    // 上传失败后重新加入队列
                uploadLimit        : 20,    // 最多上传文件数量
                successTimeout    : 30    ,//表示文件上传完成后等待服务器响应的时间。超过该时间,那么将认为上传成功。
                // 打开文件对话框 关闭时触发
                onDialogClose : function (queueData) {
                    if(queueData.filesSelected>0){
                        isComplete=false;
                        }
                    },
                
                // 选择文件对话框打开时触发
                onDialogOpen : function () { /*alert( 'please select files' ) */ },
                // 没有兼容的FLASH时触发
                onFallback : function(){ alert( '没有找到flash插件!请更新flash版本' ) },
                // 上传文件失败触发
                onUploadError : function(file, errorCode, errorMsg, errorString){ 
                    Ext.MessageBox.alert("友情提示",file.name+"上传失败!");
                    return;
            },
            //队列中的所有文件传输完毕后触发。
                onQueueComplete:function(){
                    isComplete = true;
                    Ext.MessageBox.alert("友情提示","文件上传成功!");
                },
                // 在每一个文件上传成功后触发
                onUploadSuccess : function(file, data, response) {
                            if(data != "") {
                                var strArr = data.split("#");
                                var str = strArr[0];
                            //    Ext.MessageBox.alert("友情提示",str);
                            //return;
                            }else {
                                $('#uploadify').uploadify('cancel',file.id);
                            }
                 }
            });
        });
        
        function cancelAll() {
            isComplete=true;
            $('#uploadify').uploadify('cancel','*');
        }
        function cancelFirst() {
            $('#uploadify').uploadify('cancel');
        }
        function stopAll() {
            $('#uploadify').uploadify('stop', '*');
        }
        function startAll() {
            $('#uploadify').uploadify('upload', '*');
        }
        function closeWindow() {
            if(isComplete == true){
            parent.fileIds(ids, "");
            parent.closeUploadwin();
            }
            else{
                Ext.MessageBox.alert("友情提示","请等待文件上传完毕,文件名后方出现\"complete\"即为完成!");
            }
        }
        parent.uploadwindow.on("close",function(){
            parent.fileIds("", "");
        });
    </script>



</head>
<body>
    <input type="hidden"  value="${msm_ticket_sessionID}"  id="msm_ticket_sessionID"  name="msm_ticket_sessionID">    
    <input type="hidden"  value="${uuid}"  id="uuid"  name="uuid">    
    <input type="hidden"  value="${JSESSIONID}"  id="JSESSIONID"  name="JSESSIONID">    
    <div style="padding-bottom: 10px;padding-top:10px;">
        <a href="javascript:void(0)"  class="easyui-linkbutton"  iconCls="icon-remove"  onclick="cancelAll()" >清除文件队列</a>
        <a href="javascript:void(0)" class="easyui-linkbutton"  iconCls="icon-up"  onclick="stopAll()">停止上传所有文件</a>
        <a href="javascript:void(0)"  class="easyui-linkbutton"  iconCls="icon-add"  onclick="startAll()">开始上传所有文件</a>
        <a href="javascript:void(0)" class="easyui-linkbutton"  iconCls="icon-back" onclick="closeWindow()">返回</a>
    </div>
    <span id="uploadify"></span>
    <div id="fileQueue"></div>
</body>
</html>
View Code

这里有发现一个bug ,不知道是不兼容还是bug ,火狐的某些版本 会发现session丢了 。

所以在跳转的这个页面的时候吧session的一些信息传了过来

/**
     * 跳转到附件上传页面 lwh 2018年9月19日 下午2:26:46
     * 
     * @return
     */
    @RequestMapping("/fileUploadPage")
    public String toFileUploadPage(HttpServletRequest request) {
        Cookie[] cookie = request.getCookies();
        String uuid = request.getParameter("uuid");
        String sid = "";
        String jsid = "";
        for (int i = 0; i < cookie.length; i++) {
            Cookie cook = cookie[i];
            if ("msm_ticket_sessionID".equalsIgnoreCase(cook.getName())) {
                sid = cook.getValue().toString();
            }
            if ("JSESSIONID".equalsIgnoreCase(cook.getName())) {
                jsid = cook.getValue().toString();
            }
        }
        request.setAttribute("msm_ticket_sessionID", sid);
        request.setAttribute("JSESSIONID", jsid);
        request.setAttribute("uuid", uuid);
        return "attach/FileUploadPage";
    }

这个问题不止我出现 网上也有一些解决的方法 ,我个人是这么解决的 。还有就是 用这个插件的时候 浏览器不能禁用flash插件

ps:只要和flash有关的东西用户体验都不会好到哪里去 ~  uploadify有h5的插件 但是 要钱!!!还不支持低版本浏览器。

以上内容为本人自学及总结,如有错误,请大家指出并提示我更正。谢谢!

猜你喜欢

转载自www.cnblogs.com/easyunion/p/9857163.html