jQuery上傳文件控件Uploadify使用


http://blog.csdn.net/aqsunkai/article/details/51779184

Uploadify是JQuery的一個上傳插件,支持ajax無刷新上傳,多個文件同時上傳,上傳進行進度顯示,刪除已上傳文件等。

首先應下載jQuery和uploadify插件

jQuery下載地址:http://www.jq22.com/jquery-info122

Uploadify下載地址:http://www.uploadify.com/,點擊Flash Version

jsp頁面需要引入:

[html]  view plain  copy
 
  1. <script src="<%=basePath%>resources/js/jquery-2.1.4/jquery.min.js"></script>  
  2. <script src="<%=basePath%>resources/js/uploadify/jquery.uploadify.min.js"></script>  
  3. <link type="text/css" rel="stylesheet" href="<%=basePath%>resources/js/uploadify/uploadify.css">  

html代碼:

[html]  view plain  copy
 
  1. <div>  
  2.      <input type="file" name="uploadify" id="uploadFile" />  
  3.      <div id="some_file_queue"></div>  
  4.      <div  id="fileName"></div>  
  5.      <div style="clear: both;margin-top: 20px;cursor: pointer;">  
  6.           <a  
  7.              class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary a-btn"  
  8.              onclick="javascript:$('#uploadFile').uploadify('upload','*')">  
  9.              <span class="glyphicon glyphicon-play"></span<span  
  10.              class="ui-button-text">開始上傳</span>  
  11.           </a><a  
  12.              class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-primary a-btn"  
  13.              onclick="javascript:$('#uploadFile').uploadify('cancel','*')">  
  14.              <span class="glyphicon glyphicon-ban-circle"></span<span  
  15.              class="ui-button-text">取消上傳</span>  
  16.           </a>  
  17.      </div>  
  18. </div>  

js代碼:

[javascript]  view plain  copy
 
  1. $(function() {  
  2.        $("#uploadFile").uploadify({  
  3.            'swf'           : '<%=basePath%>resources/js/uploadify/uploadify.swf',  
  4.            'uploader'      : '<%=basePath%>file/uploadFile',  //服務器端方法  
  5.            //'formData'    : {'someKey' : 'someValue', 'someOtherKey' : 1},//傳輸數據json格式  
  6.            'height'        : 30,  //按鈕高度  
  7.            'width'         : 100,  //按鈕寬度    
  8.            'fileObjName'   : 'uploadify',//默認 Filedata, $_FILES控件name名稱  
  9.            'multi'         : true,  //設置是否允許一次選擇多個文件,true為允許,false不允許  
  10.            'auto'          : false,  //是否自動上傳  
  11.            'buttonText'    : '選擇文件',//按鈕顯示文字  
  12.            //'buttonClass' : 'uuid', //按鈕輔助class  
  13.            'buttonCursor'  : 'hand', //設置鼠標移到按鈕上的開狀,接受兩個值'hand'和'arrow'(手形和箭頭)  
  14.            'debug'         : false, //開啟或關閉debug模式  
  15.            'cancelImg'     : '<%=basePath%>resources/js/img/uploadify-cancel.png', //這個沒測試出來,默認是放在與uploadify同級的img文件夾下  
  16.            'fileTypeExts'  : '*.jpg;*.jpge;*.gif;*.psd;*.png;*.txt;*.doc;*.docx;*.ppt;*.pptx;*.pdf', //文件后綴限制 默認:'*.*'  
  17.            'fileSizeLimit' : '10MB',//接受一個單位(B,KB,MB,GB)。如果是數字則默認單位為KB。設置為0時表示不限制  
  18.            'fileTypeDesc'  : 'All Files',//可選文件的描述。這個值出現在文件瀏覽窗口中的文件類型下拉選項中。(chrome下不支持,會顯示為'自定義文件',ie and firefox下可顯示描述)  
  19.            'method'        : 'post', //提交上傳文件的方法,接受post或get兩個值,默認為post  
  20.            'progressData'  : 'percentage',//設置文件上傳時顯示數據,有‘percentage’ or ‘speed’兩個參數(百分比和速度)  
  21.            'queueID'       : 'some_file_queue',//設置上傳隊列DOM元素的ID,上傳的項目會增加進這個ID的DOM中。設置為false時則會自動生成隊列DOM和ID。默認為false  
  22.            'queueSizeLimit'  : 5,//一個隊列上傳文件數限制  
  23.            'simUploadLimit'  : 5, //一次同步上傳的文件數目  
  24.            'removeCompleted' : true, //完成時是否清除隊列 默認true    
  25.            'removeTimeout'   : 1,   //完成時清除隊列顯示秒數,默認3秒    
  26.            'requeueErrors'   : false, //設置上傳過程中因為出錯導致上傳失敗的文件是否重新加入隊列中上傳  
  27.            'successTimeout'  : 30,   //設置文件上傳后等待服務器響應的秒數,超出這個時間,將會被認為上傳成功,默認為30秒  
  28.            'uploadLimit'     : 99,  //允許上傳的最多張數   
  29.            'onUploadSuccess' : function(file, data, response) { //上傳成功  
  30.                var jdata = $.parseJSON(data);  
  31.                $("#fileName").append("<p><em name='fileName' onclick = 'downLoadFile(this)' style='color:#555555'>"+jdata.fileName+"</em><em style='color:red' onclick = 'deleteFile(this)'>刪除</em><a name='filePath' style='display:none'>"+jdata.filePath+"</a></p>");  
  32.                console.log( 'id: ' + file.id  
  33.                    + ' - 索引: ' + file.index  
  34.              + ' - 文件名: ' + file.name  
  35.              + ' - 文件大小: ' + file.size  
  36.              + ' - 類型: ' + file.type  
  37.              + ' - 創建日期: ' + file.creationdate  
  38.              + ' - 修改日期: ' + file.modificationdate  
  39.              + ' - 文件狀態: ' + file.filestatus  
  40.              + ' - 服務器端消息: ' + data  
  41.              + ' - 是否上傳成功: ' + response);  
  42.             },  
  43.             'onFallback':function(){  
  44.                alert("您未安裝FLASH控件,無法一次性上傳多個文件!請安裝FLASH控件后再試。");  
  45.             },  
  46.             onSelectError:function(file, errorCode, errorMsg){ //選擇失敗  
  47.                    switch(errorCode) {  
  48.                        case -100:    
  49.                            alert("上傳的文件數量已經超出系統限制的"+$('#uploadFile').uploadify('settings','queueSizeLimit')+"個文件!");      
  50.                            break;    
  51.                        case -110:    
  52.                         alert("文件 ["+file.name+"] 大小超出系統限制的"+$('#uploadFile').uploadify('settings','fileSizeLimit')+"大小!");  
  53.                            break;    
  54.                        case -120:    
  55.                            alert("文件 ["+file.name+"] 大小異常!");  
  56.                            break;    
  57.                        case -130:    
  58.                            alert("文件 ["+file.name+"] 類型不正確!");  
  59.                            break;  
  60.                    }  
  61.                },  
  62.               /* //上傳匯總 
  63.              'onUploadProgress' : function(file, bytesUploaded, bytesTotal, totalBytesUploaded, totalBytesTotal) {   
  64.                  $('#progress').html(totalBytesUploaded + ' bytes uploaded of ' + totalBytesTotal + ' bytes.');   
  65.               }, 
  66.              'onUploadComplete' : function(file) { //上傳完成   
  67.                   console.log('The file ' + file.name + ' finished processing.');   
  68.               },   
  69.               //修改formData數據 ,每個文件即將上傳前觸發 
  70.               'onUploadStart' : function(file) { 
  71.                   $("#uploadFile").uploadify("settings", "someOtherKey", 2); 
  72.               }, 
  73.               //刪除時觸發   
  74.               'onCancel' : function(file) { 
  75.                   alert('The file ' + file.name + '--' + file.size + ' was cancelled.');   
  76.               }, 
  77.               //清除隊列   
  78.               'onClearQueue' : function(queueItemCount) { 
  79.                   alert(queueItemCount + ' file(s) were removed from the queue');   
  80.               }, 
  81.               //調用destroy是觸發   
  82.               'onDestroy' : function() {   
  83.                   alert('我被銷毀了');   
  84.               },   
  85.               //每次初始化一個隊列是觸發   
  86.               'onInit' : function(instance){   
  87.                   alert('The queue ID is ' + instance.settings.queueID);   
  88.               },  
  89.               //上傳錯誤   
  90.               'onUploadError' : function(file, errorCode, errorMsg, errorString) { 
  91.                   alert('The file ' + file.name + ' could not be uploaded: ' + errorString);   
  92.               }, */  
  93.        });  
  94. });  

頁面展示:

后台代碼:

   上傳方法

 

[java]  view plain  copy
 
  1. @RequestMapping("/uploadFile")  
  2. public void uploadFile(  
  3.     @RequestParam(value = "uploadify", required = false) MultipartFile file,  
  4.     HttpServletRequest request, HttpServletResponse response) throws IOException {  
  5.     String fileName = file.getOriginalFilename();  
  6.     Map<String, Object> dataMap = new HashMap<String, Object>();  
  7.     //本機測試路徑  
  8.     String path = request.getSession().getServletContext().getRealPath("files");  
  9.     String uuid = UUID.randomUUID().toString();  
  10.     String filePath = uuid + fileName.substring(fileName.lastIndexOf("."));  
  11.     File targetFile = new File(path, filePath);  
  12.     if (!targetFile.exists()) {  
  13.         targetFile.mkdirs();  
  14.     }  
  15.     try {  
  16.         file.transferTo(targetFile);  
  17.         dataMap.put("filePath", filePath);  
  18.         dataMap.put("fileName", fileName);  
  19.         logger.info("文件上傳成功");  
  20.     } catch (Exception e) {  
  21.             logger.error(e.getMessage());  
  22.     }  
  23.     ObjectMapper mapper = new ObjectMapper();  
  24.     String data =mapper.writeValueAsString(dataMap);  
  25.     response.setContentType("text/html;charset=UTF-8");  
  26.     response.getWriter().print(data);  
  27. }  

 

   下載方法

 

[java]  view plain  copy
 
  1. @RequestMapping("/downLoadFile")  
  2.     public void downLoadFile(HttpServletRequest req,HttpServletResponse resp,FileDTO fileDTO) throws IOException{  
  3.         logger.info("/file/downLoadFile");  
  4.         PrintWriter pw = null;  
  5.         resp.setContentType("text/html,charset=utf-8");  
  6.         resp.setCharacterEncoding("UTF-8");  
  7.         try {  
  8.             String path = req.getSession().getServletContext().getRealPath("/files")+ File.separator +fileDTO.getFilePath();  
  9.             File dir = new File(path);  
  10.             if (!dir.exists()) {  
  11.                 pw=resp.getWriter();  
  12.                 pw.print("<script>alert('抱歉,文件不存在');location.href='javascript:history.go(-1)';</script>);");  
  13.                 return;  
  14.             }  
  15.             FileInputStream in = new FileInputStream(path);  
  16.             OutputStream fos = resp.getOutputStream();  
  17.             resp.reset();  
  18.             resp.setContentType("application/x-download");  
  19.             resp.setHeader("Content-disposition", "attachment;filename="+getFileName(req,fileDTO.getFileName()));  
  20.             byte[] b = new byte[2048];  
  21.             int read;  
  22.             while ((read = in.read(b)) != -1) {  
  23.                 fos.write(b,0,read);  
  24.             }  
  25.             fos.flush();  
  26.             in.close();  
  27.             fos.close();  
  28.          } catch (FileNotFoundException e) {  
  29.             System.out.println(e.getMessage());  
  30.             pw=resp.getWriter();  
  31.             pw.print("<script>alert('抱歉,文件下載失敗');location.href='javascript:history.go(-1)';</script>);");  
  32.          }  
  33.     }  
  34.     public String getFileName(HttpServletRequest req,String channelFileName) throws UnsupportedEncodingException{  
  35.         String fileName="";  
  36.         String userAgent = req.getHeader("User-Agent");   
  37.          //針對IE或者以IE為內核的瀏覽器,加上win10自帶的Edge瀏覽器  
  38.          if (userAgent.contains("MSIE")||userAgent.contains("Trident")||userAgent.contains("Edge")) {  
  39.          fileName = java.net.URLEncoder.encode(channelFileName, "UTF-8");  
  40.         } else {  
  41.          //非IE瀏覽器的處理:  
  42.          fileName = new String(channelFileName.getBytes("UTF-8"),"ISO-8859-1");  
  43.         }  
  44.          return fileName;  
  45.     }  
[java]  view plain  copy
 
  1. package com.cn.entity;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. public class FileDTO implements Serializable{  
  6.   
  7.     /** 
  8.      *  
  9.      */  
  10.     private static final long serialVersionUID = -2487063172455865142L;  
  11.   
  12.     private int id;  
  13.     private String fileName;  
  14.     private String filePath;  
  15.     public int getId() {  
  16.         return id;  
  17.     }  
  18.     public void setId(int id) {  
  19.         this.id = id;  
  20.     }  
  21.     public String getFileName() {  
  22.         return fileName;  
  23.     }  
  24.     public void setFileName(String fileName) {  
  25.         this.fileName = fileName;  
  26.     }  
  27.     public String getFilePath() {  
  28.         return filePath;  
  29.     }  
  30.     public void setFilePath(String filePath) {  
  31.         this.filePath = filePath;  
  32.     }  
  33.       
  34. }  


免責聲明!

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



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