jquery file upload示例


原文鏈接:http://blog.csdn.net/qq_37936542/article/details/79258158

jquery file upload是一款實用的上傳文件插件,項目中剛好用到,在這里記錄分享一下。


一:准備相關js文件

jquery file upload 下載地址:點擊打開鏈接  點擊下面紅圈中的按鈕下載



jquery.js下載地址:點擊打開鏈接


二:導入js文件

注意:js文件引入的先后順序不可以亂

[html] view plain copy
  1. <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>  
  2. <!-- jquery file upload相關js -->  
  3. <script src="js/jquery.ui.widget.js"></script>  
  4. <script src="js/jquery.iframe-transport.js"></script>  
  5. <script src="js/jquery.fileupload.js"></script>  
  6. <script src="js/jquery.fileupload-process.js"></script>  
  7. <script src="js/jquery.fileupload-validate.js"></script>  


三:jsp代碼

[html] view plain copy
  1. <style>  
  2. /* input樣式 */  
  3. #uploadImg{  
  4. display: none;  
  5. }  
  6.   
  7. /* button樣式 */  
  8. #chooseFile{  
  9. background: #93b6fc;  
  10. }  
  11.   
  12. #uploadFile,#rechooseFile {  
  13. display: none;  
  14. background: #93b6fc;  
  15. }  
  16.   
  17. #image{  
  18.   width:200px;  
  19.   height:200px;  
  20. }  
  21.   
  22. /* 進度條樣式 */  
  23. .bar {   
  24.  background-image: -webkit-linear-gradient(top,#5cb85c 0,#449d44 100%);   
  25.  background-image: -o-linear-gradient(top,#5cb85c 0,#449d44 100%);   
  26.  background-image: -webkit-gradient(linear,left top,left bottom,from(#5cb85c),to(#449d44));   
  27.  background-image: linear-gradient(to bottom,#5cb85c 0,#449d44 100%);   
  28.  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c'endColorstr='#ff449d44'GradientType=0);   
  29.  background-repeat: repeat-x;   
  30.  height: 20px;   
  31.  line-height: 20px;   
  32.  -webkit-box-shadow: inset 0 -1px 0 rgba(0,0,0,.15);   
  33.  box-shadow: inset 0 -1px 0 rgba(0,0,0,.15);   
  34.  -webkit-transition: width .6s ease;   
  35.  -o-transition: width .6s ease;   
  36.  transition: width .6s ease;   
  37. }  
  38. #progress {   
  39.  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffebebeb'endColorstr='#fff5f5f5'GradientType=0);   
  40.  background-repeat: repeat-x;   
  41.  height: 20px;   
  42.  width: 0%;   
  43.  margin-bottom: 20px;   
  44.  overflow: hidden;   
  45.  background-color: #f5f5f5;   
  46.  border-radius: 4px;   
  47.  -webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,.1);   
  48.  box-shadow: inset 0 1px 2px rgba(0,0,0,.1);   
  49.  margin-top: 20px;   
  50. }  
  51. </style>  
  52. <body>  
  53.     <div class="jquery-fileupload">  
  54.         <div class="">  
  55.             <input id="uploadImg" type="file" name="uploadImg" multiple style="display: none" />   
  56.                 <button id="chooseFile">+選擇文件</button>   
  57.                 <button id="uploadFile">~開始上傳</button>  
  58.                 <button id="rechooseFile">+重新選擇</button>  
  59.         </div>  
  60.         <div>  
  61.             <img id="image" src="">  
  62.         </div>  
  63.         <div id="progress">  
  64.             <div class="bar" style="width: 0%;"></div>  
  65.         </div>  
  66.     </div>  
  67. </body>  

四:js代碼

[html] view plain copy
  1. $(function() {  
  2.   
  3.         $("#chooseFile").on("click", function() {  
  4.             $("#uploadImg").click();  
  5.         });  
  6.   
  7.         $('#uploadImg').fileupload({  
  8.             url : '/FileTest/upload',//請求發送的目標地址  
  9.             Type : 'POST',//請求方式 ,可以選擇POST,PUT或者PATCH,默認POST  
  10.             //dataType : 'json',//服務器返回的數據類型  
  11.             autoUpload : false,  
  12.             acceptFileTypes : /(gif|jpe?g|png)$/i,//驗證圖片格式  
  13.             maxNumberOfFiles : 1,//最大上傳文件數目  
  14.             maxFileSize : 1000000, // 文件上限1MB  
  15.             minFileSize : 100,//文件下限  100b  
  16.             messages : {//文件錯誤信息  
  17.                 acceptFileTypes : '文件類型不匹配',  
  18.                 maxFileSize : '文件過大',  
  19.                 minFileSize : '文件過小'  
  20.             }  
  21.         })  
  22.         //圖片添加完成后觸發的事件  
  23.         .on("fileuploadadd", function(e, data) {  
  24.             //validate(data.files[0])這里也可以手動來驗證文件格式和大小  
  25.               
  26.             //隱藏或顯示頁面元素  
  27.             $('#progress .bar').css(   
  28.                 'width', '0%'  
  29.               );  
  30.             $('#progress').hide();  
  31.             $("#chooseFile").hide();  
  32.             $("#uploadFile").show();  
  33.             $("#rechooseFile").show();  
  34.               
  35.             //獲取圖片路徑並顯示  
  36.             var url = getUrl(data.files[0]);  
  37.             $("#image").attr("src", url);  
  38.               
  39.             //綁定開始上傳事件  
  40.             $('#uploadFile').click(function() {  
  41.                 $("#uploadFile").hide();  
  42.                 jqXHR = data.submit();  
  43.                 //解綁,防止重復執行  
  44.                 $("#uploadFile").off("click");   
  45.             })  
  46.               
  47.             //綁定點擊重選事件  
  48.             $("#rechooseFile").click(function(){  
  49.                 $("#uploadImg").click();  
  50.                 //解綁,防止重復執行  
  51.                 $("#rechooseFile").off("click");   
  52.             })  
  53.         })  
  54.         //當一個單獨的文件處理隊列結束觸發(驗證文件格式和大小)  
  55.         .on("fileuploadprocessalways", function(e, data) {  
  56.             //獲取文件  
  57.             file = data.files[0];  
  58.             //獲取錯誤信息  
  59.             if (file.error) {  
  60.                 console.log(file.error);  
  61.                 $("#uploadFile").hide();  
  62.             }  
  63.         })  
  64.         //顯示上傳進度條  
  65.         .on("fileuploadprogressall", function(e, data) {  
  66.             $('#progress').show();  
  67.              var progress = parseInt(data.loaded / data.total * 100, 10);   
  68.               $('#progress').css(   
  69.                'width','15%'  
  70.               );   
  71.               $('#progress .bar').css(   
  72.                'width',progress + '%'  
  73.               );   
  74.         })  
  75.         //上傳請求失敗時觸發的回調函數  
  76.         .on("fileuploadfail", function(e, data) {  
  77.             console.log(data.errorThrown);  
  78.         })  
  79.         //上傳請求成功時觸發的回調函數  
  80.         .on("fileuploaddone", function(e, data) {  
  81.             alert(data.result);  
  82.               
  83.         })  
  84.         //上傳請求結束后,不管成功,錯誤或者中止都會被觸發  
  85.         .on("fileuploadalways", function(e, data) {  
  86.   
  87.         })  
  88.   
  89.           
  90.         //手動驗證  
  91.         function validate(file) {  
  92.             //獲取文件名稱  
  93.             var fileName = file.name;  
  94.             //驗證圖片格式  
  95.             if (!/.(gif|jpg|jpeg|png|gif|jpg|png)$/.test(fileName)) {  
  96.                 console.log("文件格式不正確");  
  97.                 return true;  
  98.             }  
  99.             //驗證excell表格式  
  100.             /*  if(!/.(xls|xlsx)$/.test(fileName)){  
  101.                 alert("文件格式不正確");  
  102.                 return true;  
  103.              } */  
  104.   
  105.             //獲取文件大小  
  106.             var fileSize = file.size;  
  107.             if (fileSize > 1024 * 1024) {  
  108.                 alert("文件不得大於一兆")  
  109.                 return true;  
  110.             }  
  111.             return false;  
  112.         }  
  113.   
  114.         //獲取圖片地址  
  115.         function getUrl(file) {  
  116.             var url = null;  
  117.             if (window.createObjectURL != undefined) {  
  118.                 url = window.createObjectURL(file);  
  119.             } else if (window.URL != undefined) {  
  120.                 url = window.URL.createObjectURL(file);  
  121.             } else if (window.webkitURL != undefined) {  
  122.                 url = window.webkitURL.createObjectURL(file);  
  123.             }  
  124.             return url;  
  125.         }  
  126.   
  127.     });  


五:服務器端代碼


1:導入依賴

[html] view plain copy
  1. <dependency>  
  2.     <groupId>commons-fileupload</groupId>  
  3.     <artifactId>commons-fileupload</artifactId>  
  4.     <version>1.3.1</version>  
  5. </dependency>  

2:配置springmvc上傳解析器
[html] view plain copy
  1. <!-- springmvc文件上傳解析器 -->  
  2. <bean id="multipartResolver"  
  3.     class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  4.     <property name="defaultEncoding" value="UTF-8" />  
  5.     <property name="maxUploadSize" value="-1" />  
  6. </bean>  

3:java代碼
[html] view plain copy
  1. package com.mote.upload;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.text.SimpleDateFormat;  
  7. import java.util.Date;  
  8.   
  9. import javax.servlet.http.HttpServletRequest;  
  10.   
  11. import org.apache.commons.io.FileUtils;  
  12. import org.springframework.stereotype.Controller;  
  13. import org.springframework.web.bind.annotation.RequestMapping;  
  14. import org.springframework.web.bind.annotation.RequestMethod;  
  15. import org.springframework.web.bind.annotation.RequestParam;  
  16. import org.springframework.web.bind.annotation.ResponseBody;  
  17. import org.springframework.web.multipart.MultipartFile;  
  18.   
  19. @Controller  
  20. public class FileUploadController {  
  21.       
  22.     /**  
  23.      * 將圖片上傳到服務器根目錄下  
  24.      * @param @param multipartFile  
  25.      * @param @param request  
  26.      * @param @return  
  27.      * @return String  
  28.      * @throws  
  29.      */  
  30.     @RequestMapping(value = "/upload",method=RequestMethod.POST)  
  31.     @ResponseBody  
  32.     public String upload(  
  33.             @RequestParam("uploadImg") MultipartFile multipartFile,  
  34.             HttpServletRequest request) {  
  35.         try {  
  36.             //獲取項目路徑  
  37.             String realPath = request.getSession().getServletContext()  
  38.                     .getRealPath("");  
  39.             InputStream inputStream = multipartFile.getInputStream();  
  40.             String contextPath = request.getContextPath();  
  41.             //服務器根目錄的路徑  
  42.             String path = realPath.replace(contextPath.substring(1), "");  
  43.             //根目錄下新建文件夾upload,存放上傳圖片  
  44.             String uploadPath = path + "upload";  
  45.             //獲取文件名稱  
  46.             String filename = getUploadFileName(multipartFile);  
  47.             //將文件上傳的服務器根目錄下的upload文件夾  
  48.             File file = new File(uploadPath, filename);  
  49.             FileUtils.copyInputStreamToFile(inputStream, file);  
  50.             //返回圖片訪問路徑  
  51.             String url = request.getScheme() + "://" + request.getServerName()  
  52.                     + ":" + request.getServerPort() + "/upload/" + filename;  
  53.             return url;  
  54.         } catch (IOException e) {  
  55.             e.printStackTrace();  
  56.         }  
  57.         return null;  
  58.   
  59.     }  
  60.       
  61.       
  62.     /**  
  63.      * 獲取上傳文件的名稱,新文件名為原文件名加上時間戳  
  64.      *  
  65.      * @param multipartFile  
  66.      *            multipartFile  
  67.      * @return 文件名  
  68.      */  
  69.     private String getUploadFileName(MultipartFile multipartFile) {  
  70.         String uploadFileName = multipartFile.getOriginalFilename();  
  71.         String fileName = uploadFileName.substring(0,  
  72.                 uploadFileName.lastIndexOf("."));  
  73.         String type = uploadFileName.substring(uploadFileName.lastIndexOf("."));  
  74.         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");  
  75.         String timeStr = sdf.format(new Date());  
  76.         String name = fileName + "_" + timeStr + type;  
  77.         return name;  
  78.     }  
  79.   
  80. }  

文末福利:

福利一:前端,Java,產品經理,微信小程序,Python等8G資源合集大放送:https://www.jianshu.com/p/e8197d4d9880
福利二:微信小程序入門與實戰全套詳細視頻教程



領取方式:
如果需要學習視頻,歡迎關注 【編程微刊】微信公眾號,回復【領取資源】一鍵領取以下所有干貨資源,獲取更多有用技術干貨、文檔資料。所有文檔會持續更新,歡迎關注一起成長!




免責聲明!

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



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