jquery file upload示例

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

jquery file upload是一款实用的上传文件插件,项目中刚好用到,在这里记录分享一下。


一:准备相关js文件

jquery file upload 下载地址:点击打开链接  点击下面红圈中的按钮下载



jquery.js下载地址:点击打开链接


二:导入js文件

注意:js文件引入的先后顺序不可以乱

  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代码

  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.   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.   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=" 0%;"></div>  
  65.         </div>  
  66.     </div>  
  67. </body>  

四:js代码

  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:导入依赖

  1. <dependency>  
  2.     <groupId>commons-fileupload</groupId>  
  3.     <artifactId>commons-fileupload</artifactId>  
  4.     <version>1.3.1</version>  
  5. </dependency>  

2:配置springmvc上传解析器
  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代码
  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
福利二:微信小程序入门与实战全套详细视频教程



领取方式:
如果需要学习视频,欢迎关注 【编程微刊】微信公众号,回复【领取资源】一键领取以下所有干货资源,获取更多有用技术干货、文档资料。所有文档会持续更新,欢迎关注一起成长!



原文地址:https://www.cnblogs.com/wangting888/p/9701648.html