Java實現文件上傳-按鈕彈出上傳頁面


轉自: https://blessht.iteye.com/blog/1405057

最近自己在做一個小系統玩的時候涉及到了文件的上傳,於是在網上找到Java上傳文件的方案,最后確定使用common-fileupload實現上傳操作。

 

  • 需求說明

用戶添加頁面有一個“上傳”按鈕,點擊按鈕彈出上傳界面,上傳完成后關閉上傳界面。

 

  • 所需Jar包

commons.fileupload-1.2.0.jar、commons.logging-1.1.1.jar、commons.beanutils-1.8.0.jar、commons.collections-3.2.0.jar、commons.io-1.4.0.jar、commons.lang-2.1.0.jar

 

  • 實現效果



 

 

  •  代碼實現
首先編寫核心代碼,Javascript打開上傳頁面,並且從上傳頁獲取返回參數,最后數據返回給回調函數callback:
 
  1 <%@ page language="java" contentType="text/html; charset=UTF-8"
  2     pageEncoding="UTF-8"%>
  3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4 <html>
  5 <head>
  6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  7 <title>定義input type="file" 的樣式</title>
  8 <style type="text/css">
  9 body {
 10     font-size: 14px;
 11 }
 12 
 13 input {
 14     vertical-align: middle;
 15     margin: 0;
 16     padding: 0
 17 }
 18 
 19 .file-box {
 20     position: relative;
 21     width: 340px
 22 }
 23 
 24 .txt {
 25     height: 22px;
 26     border: 1px solid #cdcdcd;
 27     width: 180px;
 28 }
 29 
 30 .btn {
 31     background-color: #FFF;
 32     border: 1px solid #CDCDCD;
 33     height: 24px;
 34     width: 70px;
 35 }
 36 
 37 .file {
 38     position: absolute;
 39     top: 0;
 40     right: 80px;
 41     height: 24px;
 42     filter: alpha(opacity : 0);
 43     opacity: 0;
 44     width: 260px
 45 }
 46 </style>
 47 <script>
 48     /** 
 49      * 跳轉到上傳頁 
 50      * functionId:功能ID 
 51      * fileType:文件類型 
 52      * maxSize:文件容量上限 
 53      * callback:回調函數,返回三個參數:文件真名、文件存放名和文件大小 
 54      用戶添加頁面相關代碼,點擊“上傳”按鈕時調用上面的核心js代碼,並且獲取返回值
 55      */
 56     function openUpload(functionId, fileType, maxSize, callback) {
 57         var url = root + "/CommonController.jhtml?method=goFileUpload&";
 58         if (functionId != null) {
 59             url = url + "functionId=" + functionId + "&";
 60         }
 61         if (fileType != null) {
 62             url = url + "fileType=" + fileType + "&";
 63         }
 64         if (maxSize != null) {
 65             url = url + "maxSize=" + maxSize;
 66         }
 67         var win = window.showModalDialog(url, "",
 68                 "dialogWidth:300px;dialogHeight:150px;scroll:no;status:no");
 69         if (win != null) {
 70             var arrWin = win.split(",");
 71             callback(arrWin[0], arrWin[1], arrWin[2]);
 72         }
 73     }
 74     <script>  
 75     .......  
 76       
 77     function openUpload_(){  
 78         openUpload(null,'JPG,GIF,JPEG,PNG','5',callback);  
 79     }  
 80       
 81     /**  
 82      * 回調函數,獲取上傳文件信息  
 83      * realName真實文件名  
 84      * saveName文件保存名  
 85      * maxSize文件實際大小  
 86      */  
 87     function callback(realName,saveName,maxSize){  
 88         $("#photo_").val(saveName);  
 89         //回調后其它操作  
 90     }  
 91     </script>  
 92 </script>
 93 </head>
 94 <body>
 95 
 96 
 97     <div class="file-box">
 98         <tr>
 99             <td>頭像:</td>
100             <td><input type="hidden" name="photo" id="photo_"></input> <input
101                 type="button" onclick="openUpload_();" value="上傳" /></td>
102         </tr>
103     </div>
104 </body>
105 </html>

文件上傳的JSP代碼,需要注意的是在head標簽內添加<base target="_self">以防止頁面跳轉時彈出新窗口,用戶選擇指定文件,點擊上傳時就提交表單訪問指定后台代碼

 

 1     <%@ include file="/WEB-INF/jsp/header.jsp" %>  
 2     <%@ page language="java" contentType="text/html; charset=UTF-8"  
 3         pageEncoding="UTF-8"%>  
 4     <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 5     <html>  
 6     <head>  
 7     <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
 8     <meta http-equiv="pragma" content="no-cache" />  
 9     <base target="_self">  
10     <title>文件上傳</title>  
11     </head>  
12     <body>  
13         <h5>文件上傳</h5><hr/>  
14         <form id="file_upload_id" name="file_upload_name" action="<%=root%>/CommonController.jhtml?method=doFileUpload" method="post" enctype="multipart/form-data">  
15             <input type="hidden" name="functionId" value="${functionId}"/>  
16             <input type="hidden" name="fileType" value="${fileType}"/>  
17             <input type="hidden" name="maxSize" value="${maxSize}"/>  
18             <div><input type="file" name="file_upload"/></div>  
19             <c:if test="${maxSize!=null}">  
20                 <div style="font: 12">文件最大不能超過${maxSize}MB</div>  
21             </c:if>  
22             <c:if test="${fileType!=null}">  
23                 <div style="font: 12">文件格式必須是:${fileType}</div>  
24             </c:if>  
25             <div><input type="submit" value="上傳"/></div>  
26         </form>  
27     </body>  
28     </html>  

 

CommonController目前有兩個方法,一個是跳轉到上傳頁面的方法,一個是執行上傳操作的方法doFileUpload,上傳方法運行的大概邏輯是:首先獲取頁面的請求參數,fileType用於限制上傳文件格式,

maxSize用於限制上傳文件最大值,隨后創建上傳目錄上傳即可。

 

  1     public class CommonController extends BaseController {  
  2         Log log = LogFactory.getLog(CommonController.class);  
  3           
  4         Properties fileUploadPro = null;  
  5         public CommonController(){  
  6             fileUploadPro = PropertiesUtil.getPropertiesByClass("fileupload.properties");  
  7         }  
  8           
  9           
 10         @Override  
 11         public ModeAndView init(HttpServletRequest request,  
 12                 HttpServletResponse response) throws ServletException, IOException {  
 13               
 14             return null;  
 15         }  
 16           
 17         /** 
 18          * 跳轉到文件上傳頁 
 19          * @param request 
 20          * @param response 
 21          * @return 
 22          * @throws ServletException 
 23          * @throws IOException 
 24          */  
 25         public ModeAndView goFileUpload(HttpServletRequest request,  
 26                 HttpServletResponse response) throws ServletException, IOException {  
 27             String functionId = request.getParameter("functionId");  
 28             String fileType = request.getParameter("fileType");  
 29             String maxSize = request.getParameter("maxSize");  
 30             ModeAndView mav = new ModeAndView("/WEB-INF/jsp/common/fileUpload.jsp");  
 31               
 32             if(functionId!=null && !"".equals(functionId.trim())){  
 33                 mav.addObject("functionId", functionId);  
 34             }  
 35             if(fileType!=null && !"".equals(fileType.trim())){  
 36                 mav.addObject("fileType", fileType);  
 37             }  
 38             if(maxSize!=null && !"".equals(maxSize.trim())){  
 39                 mav.addObject("maxSize", maxSize);  
 40             }  
 41             return mav;  
 42         }  
 43           
 44         /** 
 45          * 上傳文件 
 46          * @param request 
 47          * @param response 
 48          * @return 
 49          * @throws ServletException 
 50          * @throws IOException 
 51          */  
 52         @SuppressWarnings("unchecked")  
 53         public ModeAndView doFileUpload(HttpServletRequest request,  
 54                 HttpServletResponse response) throws ServletException, IOException {  
 55             //獲取並解析文件類型和支持最大值  
 56             String functionId = request.getParameter("functionId");  
 57             String fileType = request.getParameter("fileType");  
 58             String maxSize = request.getParameter("maxSize");  
 59               
 60             //臨時目錄名  
 61             String tempPath = fileUploadPro.getProperty("tempPath");  
 62             //真實目錄名  
 63             String filePath = fileUploadPro.getProperty("filePath");  
 64               
 65             FileUtil.createFolder(tempPath);  
 66             FileUtil.createFolder(filePath);  
 67               
 68             DiskFileItemFactory factory = new DiskFileItemFactory();  
 69             //最大緩存  
 70             factory.setSizeThreshold(5*1024);  
 71             //設置臨時文件目錄  
 72             factory.setRepository(new File(tempPath));  
 73             ServletFileUpload upload = new ServletFileUpload(factory);  
 74             if(maxSize!=null && !"".equals(maxSize.trim())){  
 75                 //文件最大上限  
 76                 upload.setSizeMax(Integer.valueOf(maxSize)*1024*1024);  
 77             }  
 78               
 79             try {  
 80                 //獲取所有文件列表  
 81                 List<FileItem> items = upload.parseRequest(request);  
 82                 for (FileItem item : items) {  
 83                     if(!item.isFormField()){  
 84                         //文件名  
 85                         String fileName = item.getName();  
 86                           
 87                         //檢查文件后綴格式  
 88                         String fileEnd = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();  
 89                         if(fileType!=null && !"".equals(fileType.trim())){  
 90                             boolean isRealType = false;  
 91                             String[] arrType = fileType.split(",");  
 92                             for (String str : arrType) {  
 93                                 if(fileEnd.equals(str.toLowerCase())){  
 94                                     isRealType = true;  
 95                                     break;  
 96                                 }  
 97                             }  
 98                             if(!isRealType){  
 99                                 //提示錯誤信息:文件格式不正確  
100                                 super.printJsMsgBack(response, "文件格式不正確!");  
101                                 return null;  
102                             }  
103                         }  
104                           
105                         //創建文件唯一名稱  
106                         String uuid = UUID.randomUUID().toString();  
107                         //真實上傳路徑  
108                         StringBuffer sbRealPath = new StringBuffer();  
109                         sbRealPath.append(filePath).append(uuid).append(".").append(fileEnd);  
110                         //寫入文件  
111                         File file = new File(sbRealPath.toString());  
112                         item.write(file);  
113                         //上傳成功,向父窗體返回數據:真實文件名,虛擬文件名,文件大小  
114                         StringBuffer sb = new StringBuffer();  
115                         sb.append("window.returnValue='").append(fileName).append(",").append(uuid).append(".").append(fileEnd).append(",").append(file.length()).append("';");  
116                         sb.append("window.close();");  
117                         super.printJsMsg(response, sb.toString());  
118                         log.info("上傳文件成功,JS信息:"+sb.toString());  
119                     }//end of if  
120                 }//end of for  
121                   
122             }catch (Exception e) {  
123                 //提示錯誤:比如文件大小  
124                 super.printJsMsgBack(response, "上傳失敗,文件大小不能超過"+maxSize+"M!");  
125                 log.error("上傳文件異常!",e);  
126                 return null;  
127             }  
128               
129             return null;  
130         }  
131     }  

 

至此一個文件上傳即已實現,而且能夠基本滿足不同模塊的上傳通用性,我還留着個functionId參數用於以后針對不同模塊上傳文件到不同目錄。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM