JQuery Uploadify v3.2.1 上传图片并预览(基于spring mvc框架开发)

http://blog.csdn.net/java0311/article/details/44885933

Controller后台处理:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.news.controller;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.IOException;  
  6. import java.io.OutputStream;  
  7. import java.text.SimpleDateFormat;  
  8. import java.util.Date;  
  9. import java.util.Map;  
  10. import java.util.Random;  
  11.   
  12. import javax.servlet.http.HttpServletRequest;  
  13. import javax.servlet.http.HttpServletResponse;  
  14.   
  15. import org.springframework.stereotype.Controller;  
  16. import org.springframework.util.FileCopyUtils;  
  17. import org.springframework.web.bind.annotation.RequestMapping;  
  18. import org.springframework.web.multipart.MultipartFile;  
  19. import org.springframework.web.multipart.MultipartHttpServletRequest;  
  20.   
  21. @Controller  
  22. @RequestMapping("/upload")  
  23. public class UpLoadIMGController {  
  24.       
  25.     @RequestMapping("/uploadIMG")  
  26.     public void uploadIMG(HttpServletRequest request, HttpServletResponse response) throws Exception{  
  27.         MultipartHttpServletRequest multipartRequest =  (MultipartHttpServletRequest) request;  
  28.         Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();      
  29.         String ctxPath=request.getSession().getServletContext().getRealPath("/")+"uploadFiles";  
  30.         ctxPath +=  File.separator;    
  31.         // 创建文件夹    
  32.         File file = new File(ctxPath);      
  33.         if (!file.exists()) {      
  34.         file.mkdirs();      
  35.         }  
  36.         String fileName = null;   
  37.         String newName = null;  
  38.         for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {      
  39.         // 上传文件     
  40.         MultipartFile mf = entity.getValue();    
  41.         fileName = mf.getOriginalFilename();//获取原文件名  
  42.         //获得当前时间的最小精度  
  43.         SimpleDateFormat format =  new SimpleDateFormat("yyyyMMddHHmmssSSS");  
  44.         newName = format.format(new Date());  
  45.         //获得三位随机数  
  46.         Random random = new Random();  
  47.         for(int i = 0; i < 3; i++){  
  48.             newName = newName + random.nextInt(9);  
  49.         }  
  50.         File uploadFile = new File(ctxPath + newName+fileName.substring(fileName.lastIndexOf(".")));  
  51.         try {    
  52.         FileCopyUtils.copy(mf.getBytes(), uploadFile);   
  53.        } catch (IOException e){  
  54.              e.printStackTrace();    
  55.        }  
  56.     }  
  57.         response.setHeader("Content-type""text/html;charset=UTF-8");  
  58.         response.setCharacterEncoding("UTF-8");  
  59.         response.getWriter().write(newName+fileName.substring(fileName.lastIndexOf(".")));  
  60.     }  
  61.       
  62.     @RequestMapping("/getImg")  
  63.     public void getImg(HttpServletRequest request, HttpServletResponse response) throws Exception{  
  64.         String file = request.getParameter("file");  
  65.         String path = request.getSession().getServletContext().getRealPath("/")+"uploadFiles"+File.separator+file;  
  66.         File pic = new File(path);  
  67.         FileInputStream fis = new FileInputStream(pic);  
  68.         OutputStream os = response.getOutputStream();  
  69.         try {  
  70.             int count = 0;  
  71.             byte[] buffer = new byte[1024 * 1024];  
  72.             while ((count = fis.read(buffer)) != -1)  
  73.                 os.write(buffer, 0, count);  
  74.             os.flush();  
  75.         } catch (IOException e) {  
  76.             e.printStackTrace();  
  77.         } finally {  
  78.             if (os != null)  
  79.                 os.close();  
  80.             if (fis != null)  
  81.                 fis.close();  
  82.         }  
  83.           
  84.     }  
  85. }  

jsp前台:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  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>Insert title here</title>  
  8.   
  9. <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.11.1.js"></script>  
  10. <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.uploadify.min.js"></script>  
  11. <link href="${pageContext.request.contextPath}/css/uploadify.css" rel="stylesheet" type="text/css" />  
  12.   
  13. <script type="text/javascript">  
  14.             $(function() {  
  15.                 $("#upload_org_code").uploadify({  
  16.                     'height'        : 27,  
  17.                     'width'         : 80,   
  18.                     'buttonText'    : '选择图片',  
  19.                     'swf'           : '${pageContext.request.contextPath}/css/uploadify.swf',  
  20.                     'uploader'      : '${pageContext.request.contextPath}/upload/uploadIMG',  
  21.                     'auto'          : true,  
  22.                     'multi'         : false,  
  23.                     'removeCompleted':false,  
  24.                     'cancelImg'     : '${pageContext.request.contextPath}/js/uploadify-cancel.png',  
  25.                     'fileTypeExts'  : '*.jpg;*.jpge;*.gif;*.png',  
  26.                     'fileSizeLimit' : '1MB',  
  27.                     'fileObjName'   : 'file',   
  28.                     'onUploadSuccess':function(file,data,response){  
  29.                         $('#' + file.id).find('.data').html('');  
  30.                         $("#upload_org_code_name").val(encodeURI(data));  
  31.                         $("#upload_org_code_img").attr("src","${pageContext.request.contextPath}/upload/getImg?file="+encodeURI(data));    
  32.                         $("#upload_org_code_img").show();  
  33.                     },  
  34.                     //加上此句会重写onSelectError方法【需要重写的事件】  
  35.                     'overrideEvents': ['onSelectError', 'onDialogClose'],  
  36.                     //返回一个错误,选择文件的时候触发  
  37.                     'onSelectError':function(file, errorCode, errorMsg){  
  38.                         switch(errorCode) {  
  39.                             case -110:  
  40.                                 alert("文件 ["+file.name+"] 大小超出系统限制的" + jQuery('#upload_org_code').uploadify('settings', 'fileSizeLimit') + "大小!");  
  41.                                 break;  
  42.                             case -120:  
  43.                                 alert("文件 ["+file.name+"] 大小异常!");  
  44.                                 break;  
  45.                             case -130:  
  46.                                 alert("文件 ["+file.name+"] 类型不正确!");  
  47.                                 break;  
  48.                         }  
  49.                     },  
  50.                 });  
  51.             })  
  52. </script>  
  53. </head>  
  54. <body>  
  55. <table>  
  56.     <tr>  
  57.          <td align="right"><font style="color: red;">*</font>组织代码机构:</td>  
  58.          <td>  
  59.              <table>  
  60.                  <tr>  
  61.                      <td width="45%"><input type="file" name="upload_org_code" id="upload_org_code"/></td>  
  62.                      <td><img style="display: none" id="upload_org_code_img" src="" width="150" height="150"></td>  
  63.                   </tr>  
  64.               </table>  
  65.               <input type="hidden" name="upload_org_code_name" id="upload_org_code_name" />  
  66.               <hr>  
  67.           </td>  
  68.       </tr>  
  69. </table>  
  70. </body>  
  71. </html>  



特别注意:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. $("#upload_org_code_img").attr("src","${pageContext.request.contextPath}/upload/getImg?file="+encodeURI(data));   
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. 如果报未找到文件,不进请求方法的。请在方法处加上<span style="font-size:24px;color:#ff0000;"><strong>.do</strong></span>  
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <pre code_snippet_id="636289" snippet_file_name="blog_20150405_2_30604" name="code" class="html"> $("#upload_org_code_img").attr("src","${pageContext.request.contextPath}/upload/getImg<span style="color:#ff0000;"><strong>.do</strong></span>?file="+encodeURI(data));  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值