1. 程式人生 > >實現多檔案上傳的例子

實現多檔案上傳的例子

通過頁面實現多檔案上傳,並有進度條控制的例子,步驟參考如下(程式碼中涉及的幾個按鈕圖片參見附件)

1:頁面端實現多檔案上傳

?
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" session="false" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "<a href="http://www.w3.org/TR/html4/loose.dtd" "="">http://www.w3.org/TR/html4/loose.dtd"
> <html> <head> <title>上傳</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <script src="<%= request.getContextPath() %>/common/nui/nui.js" type="text/javascript"></script> <link href="<%=request.getContextPath()%>/FuJian/style/YangShi.css"
rel="stylesheet" type="text/css"/> <% String Bizid = request.getParameter("BizID"); String Typeid = request.getParameter("typeid"); String ID = request.getParameter("ID"); String Filetitle = request.getParameter("Filetitle"); %> </head> <body> <form action="<%=request.getContextPath()%>/FuJian_CunRu.jsp?BizID=<%=Bizid%>&Typeid=<%=Typeid%>&ID=<%=ID%>&Filetitle=<%=Filetitle%>"
method="post" enctype="multipart/form-data" onsubmit="return TiJiao()"> <span style='color:red;'>提示:單個檔案最大上傳為50MB,超出會紅色提示,建議壓縮後上傳!</span> <div class="fileInputContainer"> <input type="file" id="WenJian" class="fileupload" name="Fdata" onchange="XuanZhong()" multiple="multiple"/> <input type="button" value="" class="quxiao" onClick="QuXiao()"/> <input type="submit" value="" class="shangchuan"/> </div> <div id="JinDu" class="progressbar"> <div id="ZouDong" class="progressbar-percent"></div> <div class="progressbar-label"><span id="JinduTiao" style='color:red;'></span></div> </div> <div id="QWenJian"> <table id="SuoYouWJ" bordercolor="#AFD1EB" cellpadding='0' cellspacing='0' align='center' border='1px' width='100%'> <tbody id="tbody"> <tr align="center"> <td width="45%">檔名</td> <td width="7%">型別</td> <td width="38%">提示</td> </tr>     </tbody> </table> </div> </form> <script type="text/javascript"> nui.parse(); //載入 $(function(){ $("#QWenJian").hide(); }); //返回值 var XinXi = "<%=request.getParameter("FanHuiZhi") %>"; if(XinXi != "null"){ document.getElementById('ZouDong').style.width = "100%"; document.getElementById('JinduTiao').innerHTML = "進度100%"; nui.alert(XinXi,"系統提示",function(){ CloseWindow(); }); }else{ $("#JinDu").hide(); } //定義檔案大小 var DaXiao = 50*1024*1024; //選中的檔案 function XuanZhong(){ //保留Table第一行刪除剩下所有 $("table tbody tr").eq(0).nextAll().remove(); $("#QWenJian").show(); //獲取多檔案上傳的所有檔名 var SuoYouWenJian = document.getElementById("WenJian").files; for(var i=0;i<SuoYouWenJian.length;i++){ var WenJianQuanMing = SuoYouWenJian[i].name; //擷取檔名 var WenJianMing = WenJianQuanMing.substring(0,WenJianQuanMing.indexOf(".")); //擷取檔案型別轉換成小寫 var WenJianLeiXing = WenJianQuanMing.substring(WenJianQuanMing.indexOf(".")).toLowerCase(); //檔案大小 var WenJianDaXiao = SuoYouWenJian[i].size; if(parseInt(WenJianDaXiao) > parseInt(DaXiao)){ WenJianTiSHi = "檔案過大,建議壓縮後再上傳!"; }else if(parseInt(WenJianDaXiao) == 0){ WenJianTiSHi = "檔案內容為空,請核對後再上傳!"; }else if(WenJianLeiXing == ".exe" || WenJianLeiXing == ".java" || WenJianLeiXing == ".mp4"){ WenJianTiSHi = "此型別格式不支援上傳!"; }else{ WenJianTiSHi = "檔案符合!"; } //把輸入的值傳到列表裡 var MingTxt = document.createTextNode(WenJianMing); var LeiXingTxt = document.createTextNode(WenJianLeiXing); var TiShiTxt = document.createTextNode(WenJianTiSHi); //td是表中的列 tr是表中的行 var WJMing = document.createElement("td"); var WJLeiXing = document.createElement("td"); var TiShi = document.createElement("td"); if(parseInt(WenJianDaXiao) > parseInt(DaXiao) || parseInt(WenJianDaXiao) == 0){ TiShi.style.color = "#FF0000"; }else if(WenJianLeiXing == ".exe" || WenJianLeiXing == ".java" || WenJianLeiXing == ".mp4"){ TiShi.style.color = "#FF0000"; }else{ TiShi.style.color = "#00FF00"; }   //td的標籤體 -->td物件 WJMing.appendChild(MingTxt); WJLeiXing.appendChild(LeiXingTxt); TiShi.appendChild(TiShiTxt); //建立tr物件行 var HangTr = document.createElement("tr"); //td物件 -->tr物件 HangTr.appendChild(WJMing); HangTr.appendChild(WJLeiXing); HangTr.appendChild(TiShi); //tr物件 --> tbody物件 document.getElementById("tbody").appendChild(HangTr); } } var DianJi = 0; //上傳時候驗證 function TiJiao(){ if(DianJi == 0){ DianJi = 1; var SYWenJian = document.getElementById("WenJian").files; if(SYWenJian.length < 1){ nui.alert("請選擇一條檔案後,再上傳!","系統提示"); return false; }else if(SYWenJian.length > 5){ nui.alert("上傳檔案最多每次5條資訊!","系統提示"); return false; }else{ for(var i=0;i<SYWenJian.length;i++){ var FileQuanMing = SYWenJian[i].name; //擷取檔案型別轉換成小寫 var FileLX = FileQuanMing.substring(FileQuanMing.indexOf(".")).toLowerCase(); if(FileLX == ".exe" || FileLX == ".java" || FileLX == ".mp4"){ nui.alert("上傳的檔案中存在型別格式不支援上傳,請重新選擇後再上傳!","系統提示"); return false; } //檔案大小 var WenJianDaXiao = SYWenJian[i].size; //檔案內容為空 var KongDaXiao = SYWenJian[i].size; if(parseInt(WenJianDaXiao) > parseInt(DaXiao)){ nui.alert("上傳的檔案中有過大檔案,請重新選擇後再上傳!","系統提示",function(){ return false; }); } if(parseInt(KongDaXiao) == 0){ nui.alert("上傳的檔案內容是空,請核對後再上傳!","系統提示",function(){ return false; }); } } $("#JinDu").show(); JinDuTiaoXX(1); } }else{ nui.loading("請勿重複操作,請稍後......","系統提示"); return false; } } //進度條 function JinDuTiaoXX(n){ if(parseInt(n) == 97){ return; } t = parseInt(n); document.getElementById('ZouDong').style.width = parseInt(t) + "%"; document.getElementById('JinduTiao').innerHTML= "進度" + parseInt(t) +"%"; setTimeout("JinDuTiaoXX(parseInt(t)+1)",800); } //獲取子頁面資訊 function GetData(){ if(XinXi == "上傳成功!"){ return true; }else{ return false; } } //關閉子視窗,重新整理父窗體 function CloseWindow(action){ if (window.CloseOwnerWindow) return window.CloseOwnerWindow(action); else window.close(); } //點選取消按鈕 function QuXiao(e){ CloseWindow("cancel"); } </script> </body> </html>

2:檔案上傳要用到的css

?
.fileInputContainer{ background:url(../style/youlan.png) no-repeat; } .fileupload{ width:350px; height:27px; right: 0; top: 0; opacity: 0; filter:alpha(opacity=0); cursor:pointer; } .shangchuan{ background:url(../style/shangchuan.png); width:62px; height:26px; border:0; padding:0; float:right; margin-right:10px; } .quxiao{ background:url(../style/quxiao.png); width:62px; height:26px; border:0; padding:0; float:right; margin-right:10px; } .yichu{ width:62px; height:26px; border:0; padding:0; background:url(../style/yichu.png); } .progressbar{ position:relative; background:#AAAAAA; width:98%; height:16px; overflow:hidden; } .progressbar-percent{ position:absolute; height:18px; background:#00FF00; left:0;top:0px; overflow:hidden; z-index:1; } .progressbar-label{ position:absolute; left:0; top:0; width:90%; font-size:13px; color:White; z-index:10; text-align:center; height:16px; line-height:16px; }

3:檔案上傳伺服器端程式

?
0<%@page import="java.io.File"%> <%@page import="java.text.SimpleDateFormat"%> <%@page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" import="java.util.*,Test.*"%> <%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%> <%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%> <%@page import="org.apache.commons.fileupload.FileItem"%> <%@page import="java.io.FileInputStream"%> <%@page import="java.io.ByteArrayOutputStream"%> <%@page import="com.eos.data.datacontext.DataContextManager"%> <%@page import="com.eos.data.datacontext.IMUODataContext"%> <%@page import="com.eos.data.datacontext.IUserObject"%> <%@page import="com.eos.foundation.data.DataObjectUtil"%> <%@page import="commonj.sdo.DataObject"%> <%@page import="com.eos.engine.component.ILogicComponent"%> <%@page import="com.primeton.ext.engine.component.LogicComponentFactory"%> <%@page import="java.io.InputStream"%> <%@page import="java.io.PrintWriter"%> <% System.out.println("我進來了....."); //定義上傳路徑 String BenLuJing = "FuJianCaiLiao\\" + "Upload\\"; boolean isFileUpload = ServletFileUpload.isMultipartContent(request); //定義返回值 String FanHuiZhi = ""; //如果是檔案上傳型別 if(isFileUpload){ //得到檔案上傳工廠 DiskFileItemFactory GongChang = new DiskFileItemFactory(); //處理檔案上傳核心類 ServletFileUpload fileUpload = new ServletFileUpload(GongChang);  //設定檔案上傳類的編碼格式 fileUpload.setHeaderEncoding("UTF-8"); // 集合資料:FileItem物件 注意:每一個表單域 對應一個 FileItem物件(封裝) List<FileItem> fileItemList = fileUpload.parseRequest(request); //遍歷檔案 for(FileItem item: fileItemList){ //如果這個文字域是檔案型別的 if(!item.isFormField()){ //得到檔名 String FileName = item.getName(); //去除所有空格 String WenJianMing = FileName.replaceAll(" +",""); //檢查檔案字尾格式 ,並轉換為小寫 String FileLeiXing = WenJianMing.substring(WenJianMing.lastIndexOf(".")).toLowerCase();  //獲取檔案大小 long WenJianSize = item.getSize(); //轉換檔案大小名稱 long kb = 1024; long mb = kb * 1024; long gb = mb * 1024; //檔案單位 String FileSize = ""; if(WenJianSize >= gb){ FileSize = String.format("%.1fGB",(float)WenJianSize/gb); }else if (WenJianSize >= mb) { float f = (float)WenJianSize/mb; FileSize = String.format(f > 100 ? "%.0fMB" : "%.1fMB",f); }else if(WenJianSize >= kb){ float f = (float)WenJianSize/kb; FileSize = String.format(f > 100 ? "%.0fKB" : "%.1fKB",f); }else{ FileSize = String.format("%dB",WenJianSize); } //得到伺服器的根路徑 String rootPath = request.getRealPath("\\"); //定義年 SimpleDateFormat Nian = new SimpleDateFormat("yyyy"); //定義年月日 SimpleDateFormat NianYueRi = new SimpleDateFormat("yyyy-MM-dd"); //轉換成年份 String NianFen = Nian.format(new Date()); //轉換成年月日 String NianYR = NianYueRi.format(new Date()); //得到檔案的路徑 String QuanLuJIng = rootPath + BenLuJing + NianFen  + "年\\" + NianYR; //建立檔案唯一名稱  String UID = UUID.randomUUID().toString(); //擷取檔名 String FileMing = WenJianMing.substring(0,WenJianMing.indexOf(".")); //拼接一個新的檔名 String XinMing =NianFen + "_" + NianYR + "_" + FileMing + "_" + UID + FileLeiXing; //路徑 File WenJianFile = new File(QuanLuJIng); //如果年資料夾不存在則建立    if(!WenJianFile.exists() && !WenJianFile.isDirectory()){       //建立資料夾 WenJianFile.mkdirs();  } //路徑 File FileWJ = new File(QuanLuJIng + "\\" +XinMing); //得到使用者資訊 String ShangChuanRen = ""; IMUODataContext muo = DataContextManager.current().getMUODataContext(); if (muo != null) { IUserObject userobject = muo.getUserObject(); if (userobject != null) { ShangChuanRen = userobject.getUserRealName(); } } //引用實體 DataObject dataobject = DataObjectUtil.createDataObject("com.QiYeDuan.FuJianCaiLiao.FuJian.FujianXx"); String Filetitle = request.getParameter("Filetitle"); //把傳過來的filetitle解碼 String FileTitle = java.net.URLDecoder.decode(Filetitle,"UTF-8"); dataobject.set("bizid", request.getParameter("Bizid")); dataobject.set("typeid", request.getParameter("Typeid")); dataobject.set("filetypeid", request.getParameter("ID")); dataobject.set("filetitle", FileTitle); dataobject.set("filesize", FileSize); dataobject.set("fileextension", FileLeiXing); dataobject.set("url", XinMing); dataobject.set("scr", ShangChuanRen); dataobject.set("scrq", new Date()); //呼叫邏輯構建 String componentName = "com.QiYeDuan.FuJianCaiLiao.FuJian"; String operationName = "add_FuJianXX"; ILogicComponent logicComponent = LogicComponentFactory.create(componentName); // 邏輯流的輸入引數 Object[] params = new Object[1]; params[0] = dataobject; Object[] result = null; result = logicComponent.invoke(operationName, params); //存入檔案 item.write(FileWJ); }else{ FanHuiZhi  = "要長傳的路徑出現錯誤,請重新上傳!"; } } FanHuiZhi  = "上傳成功!"; }else{ FanHuiZhi  = "長傳錯誤!"; }