前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JQuery Uploadify v3.2.1 上传图片并预览(基于spring mvc框架开发)

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

作者头像
bear_fish
发布2018-09-19 16:16:55
6390
发布2018-09-19 16:16:55
举报

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

Controller后台处理:

[java] view plain copy

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

jsp前台:

[html] view plain copy

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

特别注意:

[html] view plain copy

  1. $("#upload_org_code_img").attr("src","${pageContext.request.contextPath}/upload/getImg?file="+encodeURI(data));   

[html] view plain copy

  1. 如果报未找到文件,不进请求方法的。请在方法处加上<span style="font-size:24px;color:#ff0000;"><strong>.do</strong></span>

[html] view plain copy

  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));  
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016年07月29日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档