java多附件上传 实例demo

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!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="">
    
    
    <script type="text/javascript" src="../js/swfupload/js/swfupload.js"></script>
    <script type="text/javascript" src="../js/swfupload/js/swfupload.queue.js"></script>
    <script type="text/javascript" src="../js/swfupload/js/fileprogress.js"></script>
    <script type="text/javascript" src="../js/swfupload/js/handlers.js"></script>


    <style type="text/css">
        a{
            color:blue;
            text-decoration: underline;
            font-size: 13px;
        }
    </style>
    <script type="text/javascript">
  var upload;
  window.onload = function() {
    upload = new SWFUpload({
    // 处理文件上传的url
    upload_url: "${pageContext.request.contextPath}/fileAction!uploadBatch.do",
    postName : "Filedata",//上传的file

    // 上传文件限制设置
    file_size_limit : "5MB",//指定要上传的文件的最大体积,可以带单位,合法的单位有:B、KB、MB、GB,默认为KB
    file_types : "*.jpg;*.jpeg;*.png;*.gif;*.bmp;",    //此处也可以修改成你想限制的类型,比如:*.doc;*.wpd;*.pdf
    file_types_description : "Word,Excel,Images Files",
    file_upload_limit : "200",//允许同时上传文件的个数
    file_queue_limit : "0",//允许队列存在的文件数量,默认值为0,即不限制
    
    // 事件处理设置(所有的自定义处理方法都在handler.js文件里)
    file_dialog_start_handler : fileDialogStart,
    file_queued_handler : fileQueued,
    file_queue_error_handler : fileQueueError,
    file_dialog_complete_handler : fileDialogComplete,//这里为自动上传
    upload_start_handler : uploadStart,
    upload_progress_handler : uploadProgress,
    upload_error_handler : uploadError,
    upload_success_handler : uploadSuccess,
    upload_complete_handler : uploadComplete,
    

    // 按钮设置
    button_image_url : "../js/swfupload/images/XPButtonNoText_61x22.png",    // 按钮图标
    button_placeholder_id : "spanButtonPlaceholder",
    button_ 61,
    button_height: 22,
    button_text: '&nbsp;&nbsp;浏览...',
                
    // swf设置
    flash_url : "../js/swfupload/js/swfupload.swf",
                

    custom_settings : {
        progressTarget : "fsUploadProgress",
        cancelButtonId : "btnCancel"
    },
    
        removeCompleted : true,//上传完成后自动删除队列
        use_query_string : true,//要传递参数,必须配置
        //debug模式,可以在页面看到详细信息
        debug: false
    });
  };
  
  //重写上传成功方法
  function uploadSuccess(file, serverData) {
        try {
            var progress = new FileProgress(file, this.customSettings.progressTarget);
            
            var showMsg = "<span style='margin-left:100px'></span><font color='green'>---------------上传成功,</font><a style='text-decoration: underline;color:blue;' target='_blank' href='<%=request.getAttribute("loanDownloadPath")%>" + serverData.split(":")[1] + "'>预 览</a>       <img title='删除' onclick='removeFile4Add(this,""+ serverData.split(":")[1] +"",""+serverData.split(":")[0]+"")' style='cursor: pointer;' src='../images/list_remove.png' />";
            progress.setStatus(showMsg);
            progress.toggleCancel(false);
            
            var fileObj = document.getElementById("filesLongString");
            fileObj.value = fileObj.value + serverData + "/";
            
            //alert(fileObj.value.length);

        } catch (ex) {
            this.debug(ex);
        }
    }
  
  //上传成功后的删除
  function removeFile4Add(fileIdObj,newName,oldName) {
      $.messager.confirm("删除","确认删除该附件?",function(r){//jquery easyui 提示框
            if(r) {
                  $(fileIdObj).parent().parent().parent().hide();//隐藏本行
                  
                  //转义括号和/
                  var replaceStr = oldName + ":" + newName + "/";
                  
                  replaceStr = replaceStr.replace(/(/,"\(");
                  replaceStr = replaceStr.replace(/)/,"\)");
                  replaceStr = replaceStr.replace(//,"\(");
                  replaceStr = replaceStr.replace(//,"\)");
                  
                  var reg2 = new RegExp(replaceStr,'ig');
                  
                  var fileObj = document.getElementById("filesLongString");
                  var result = fileObj.value.replace(eval(reg2),"");
                  document.getElementById("filesLongString").value = result;
            }
        });
  }
  

  </script>
  </head>
  
  <body>
      <%
/*循环上传后的附件并显示*/
String files_oldname = (String)request.getAttribute("bean.files_oldname"); String files_newname = (String)request.getAttribute("bean.files_newname"); String loanDownloadPath = (String)request.getAttribute("downloadPath"); String oldNameArr[] = null, newNameArr[] = null; if(files_oldname!=null && files_newname!=null) { oldNameArr = files_oldname.split("/"); newNameArr = files_newname.split("/"); } String filesLongString = "";//组装成新增借款时附件的格式//中文名.jpg:201506231401577954808.jpg/ Map<String,String> fileMap = new TreeMap<String,String>();//有序 if(oldNameArr!=null && newNameArr!=null) { for(int i=0; i<oldNameArr.length; i++) { fileMap.put(oldNameArr[i], newNameArr[i]); filesLongString = filesLongString + oldNameArr[i] + ":" + newNameArr[i] + "/"; } } %> <% int i = 0; for(Map.Entry<String, String> entry : fileMap.entrySet()) { i++; %> <div id="fileId<%=i%>" style="padding-top:15px"> <a target="_blank" href="<%=loanDownloadPath%><%=entry.getValue()%>"><%=entry.getKey() %></a> <s:if test="#session.s_userRole==1"> <% if(entry!=null && !"".equals(entry.getValue())) { %> <img title="删除" style="cursor: pointer;" src="../images/remove.png" onclick="removeFile('fileId<%=i%>','<%=entry.getValue()%>','<%=entry.getKey() %>')"> <% } %> </s:if> </div> <% } if(fileMap.size()==0) { //out.print("没有上传附件"); } %> <table> <tr> <td colspan="4" class="sm"> <form id="filesForm" name="filesForm" method="post" action="" enctype="multipart/form-data"> <s:token /> <div class="flash" id="fsUploadProgress"></div> <br/> <div style="padding-left: 5px;"> <font color="blue">请选择需要上传的附件:</font><span id="spanButtonPlaceholder"></span> <!-- 不能去掉'取消'按钮,否则无法上传 --> <input id="btnCancel" type="button" value="取消" onclick="cancelQueue(upload);" disabled="disabled" style="display:none;margin-left: 2px; height: 22px; font-size: 8pt;" /> <input id="clearDivId" type="button" value="清空" onclick="clear();" style="display:none"/> <br/> (提示:选择文件后会自动上传。) </div> <input type="text" style=" 500px; visibility: hidden;" id="filesLongString" name="filesLongString" value="<%=filesLongString%>"> </form> </td> </tr> </table> </body> </html>
//上传的文件到服务器
public void uploadBatch() {
        MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) ServletActionContext.getRequest();
        File[] files = wrapper.getFiles("Filedata");
        File savefile = null;
            String realpath = ServletActionContext.getServletContext().getRealPath("/upload/");//上传路径
            int randomNum = (int) (Math.random() * 10000);// 生成一个10000以内的随机数
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String fileNameStr = wrapper.getFileNames("Filedata")[0];//原名称
            String type = fileNameStr.substring(fileNameStr.lastIndexOf("."), fileNameStr.length());// 获取文件类型
            String newFileName = sdf.format(new Date()) + randomNum + type;// 当前时间作为上传后的文件名
            savefile = new File(new File(realpath), newFileName);
            savefile.setWritable(true, false);//设置可写,针对linux系统
            if (!savefile.getParentFile().exists()) {
                savefile.getParentFile().mkdirs();
            }
            
            try {
                FileUtils.copyFile(files[0], savefile);
            } catch (Exception e) {
                logger.error("上传excel异常:", e);
            }
        
        try {
            HttpServletResponse response = ServletActionContext.getResponse();
            response.setContentType("text/html; charset=UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            PrintWriter writer = response.getWriter();
            writer.print(fileNameStr + ":" + newFileName);//数据导入成功后,返回文件原名、现名到前台
            writer.flush();
            writer.close();
        } catch (IOException e) {
            logger.error(e);
        }
        
    }
原文地址:https://www.cnblogs.com/yushouling/p/4651106.html