图片上传--Upload
图片上传基于spring框架写的代码:
1.首先:我们要再springmvc中添加试图解析器:
1 <!-- 图片解析器 --> 2 <bean id="multipartResolver" 3 class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 4 <property name="maxUploadSize" value="5242880"></property> 5 <property name="defaultEncoding" value="utf-8"></property> 6 </bean>
2.然后封装一个图片返回类
1 package com.taotao.manage.bean; 2 3 public class PicUploadResult { 4 private Integer error; 5 6 private String url; 7 8 private String width; 9 10 private String height; 11 12 public Integer getError() { 13 return error; 14 } 15 16 public void setError(Integer error) { 17 this.error = error; 18 } 19 20 public String getUrl() { 21 return url; 22 } 23 24 public void setUrl(String url) { 25 this.url = url; 26 } 27 28 public String getWidth() { 29 return width; 30 } 31 32 public void setWidth(String width) { 33 this.width = width; 34 } 35 36 public String getHeight() { 37 return height; 38 } 39 40 public void setHeight(String height) { 41 this.height = height; 42 } 43 44 }
3.写一个userController
1 package com.taotao.manage.controller; 2 3 import java.awt.image.BufferedImage; 4 import java.io.File; 5 import java.io.IOException; 6 import java.util.Date; 7 8 import javax.imageio.ImageIO; 9 import javax.servlet.http.HttpServletResponse; 10 11 import org.apache.commons.lang3.RandomUtils; 12 import org.apache.commons.lang3.StringUtils; 13 import org.joda.time.DateTime; 14 import org.slf4j.Logger; 15 import org.slf4j.LoggerFactory; 16 import org.springframework.beans.factory.annotation.Autowired; 17 import org.springframework.http.MediaType; 18 import org.springframework.stereotype.Controller; 19 import org.springframework.web.bind.annotation.RequestMapping; 20 import org.springframework.web.bind.annotation.RequestMethod; 21 import org.springframework.web.bind.annotation.RequestParam; 22 import org.springframework.web.bind.annotation.ResponseBody; 23 import org.springframework.web.multipart.MultipartFile; 24 25 import com.fasterxml.jackson.databind.ObjectMapper; 26 import com.taotao.manage.bean.PicUploadResult; 27 import com.taotao.service.impl.UpLoadServiceImpl; 28 29 /** 30 * 图片上传 31 */ 32 @Controller 33 @RequestMapping("/pic") 34 public class PicUploadController { 35 36 private static final Logger LOGGER = LoggerFactory.getLogger(PicUploadController.class); 37 38 @Autowired 39 private UpLoadServiceImpl loadService; 40 private static final ObjectMapper mapper = new ObjectMapper(); 41 42 // 允许上传的格式 43 private static final String[] IMAGE_TYPE = new String[] { ".bmp", ".jpg", ".jpeg", ".gif", ".png" }; 44 45 @RequestMapping(value = "/upload", method = RequestMethod.POST) 46 @ResponseBody 47 public String upload(@RequestParam("uploadFile") MultipartFile uploadFile, HttpServletResponse response) 48 throws Exception { 49 50 // 校验图片格式 51 boolean isLegal = false; 52 for (String type : IMAGE_TYPE) { 53 if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(), type)) { 54 isLegal = true; 55 break; 56 } 57 } 58 59 // 封装Result对象,并且将文件的byte数组放置到result对象中 60 PicUploadResult fileUploadResult = new PicUploadResult(); 61 62 // 状态 圖片格式正确时为:0,错误时为:1 63 fileUploadResult.setError(isLegal ? 0 : 1); 64 65 // 文件新路径 66 String filePath = getFilePath(uploadFile.getOriginalFilename()); 67 68 if (LOGGER.isDebugEnabled()) { 69 LOGGER.debug("Pic file upload .[{}] to [{}] .", uploadFile.getOriginalFilename(), filePath); 70 } 71 72 // 生成图片的绝对引用地址 73 String picUrl = StringUtils.replace(StringUtils.substringAfter(filePath, loadService.TAOTAO_UPLOAD_RESPOSITORY), 74 "\\", "/"); 75 // 用来显示图片的路径 76 fileUploadResult.setUrl(loadService.TAOTAO_IMAGES_URL + picUrl); 77 78 File newFile = new File(filePath); 79 80 // 写文件到磁盘 81 uploadFile.transferTo(newFile); 82 83 // 校验图片是否合法 84 isLegal = false; 85 try { 86 BufferedImage image = ImageIO.read(newFile); 87 if (image != null) { 88 fileUploadResult.setWidth(image.getWidth() + ""); 89 fileUploadResult.setHeight(image.getHeight() + ""); 90 isLegal = true; 91 } 92 } catch (IOException e) { 93 } 94 95 // 状态 96 fileUploadResult.setError(isLegal ? 0 : 1); 97 98 if (!isLegal) { 99 // 不合法,将磁盘上的文件删除 100 newFile.delete(); 101 } 102 103 response.setContentType(MediaType.TEXT_HTML_VALUE); 104 return mapper.writeValueAsString(fileUploadResult); 105 } 106 107 // 获取文件路径 108 // 接受的参数时上传文件的文件名 109 private String getFilePath(String sourceFileName) { 110 // File.separator:/ 111 String baseFolder = loadService.TAOTAO_UPLOAD_RESPOSITORY + File.separator + "images"; 112 Date nowDate = new Date(); 113 // yyyy/MM/dd 114 String fileFolder = baseFolder + File.separator + new DateTime(nowDate).toString("yyyy") + File.separator 115 + new DateTime(nowDate).toString("MM") + File.separator + new DateTime(nowDate).toString("dd"); 116 File file = new File(fileFolder); 117 if (!file.isDirectory()) { 118 // 如果目录不存在,则创建目录 119 file.mkdirs(); 120 } 121 // 生成新的文件名 122 String fileName = new DateTime(nowDate).toString("yyyyMMddhhmmssSSSS") + RandomUtils.nextInt(100, 9999) + "." 123 + StringUtils.substringAfterLast(sourceFileName, "."); 124 return fileFolder + File.separator + fileName; 125 } 126 127 }
4.写页面的js代码
1 init : function(data){ 2 // 图片初始化 3 this.initPicUpload(data); 5 }, 6 // 初始化图片上传组件 7 initPicUpload : function(data){ 8 $(".picFileUpload").each(function(i,e){ 9 var _ele = $(e); 10 // 获取当前元素得兄弟元素 11 _ele.siblings("div.pics").remove(); 12 _ele.after('\ 13 <div class="pics">\ 14 <ul></ul>\ 15 </div>'); 16 // 回显图片 17 if(data && data.pics){ 18 var imgs = data.pics.split(","); 19 for(var i in imgs){ 20 if($.trim(imgs[i]).length > 0){ 21 _ele.siblings(".pics").find("ul").append("<li><a href='"+imgs[i]+"' target='_blank'><img src='"+imgs[i]+"' width='80' height='50' /></a></li>"); 22 } 23 } 24 } 25 $(e).click(function(){ 26 var form = $(this).parentsUntil("form").parent("form"); 27 KindEditor.editor(TT.kingEditorParams).loadPlugin('multiimage',function(){ 28 var editor = this; 29 editor.plugin.multiImageDialog({ 30 clickFn : function(urlList) { 31 var imgArray = []; 32 KindEditor.each(urlList, function(i, data) { 33 alert(data) 34 alert(JSON.stringify(data)); 35 imgArray.push(data.url); 36 form.find(".pics ul").append("<li><a href='"+data.url+"' target='_blank'><img src='"+data.url+"' width='80' height='50' /></a></li>"); 37 }); 38 form.find("[name=image]").val(imgArray.join(",")); 39 editor.hideDialog(); 40 } 41 }); 42 }); 43 }); 44 }); 45 }, 46
然后效果为:
OK!!!