kindeditor java 上传图片_kindeditor Springmvc 整和解决图片上传问题

1 importjava.io.File;2 importjava.io.FileOutputStream;3 importjava.io.IOException;4 importjava.text.SimpleDateFormat;5 importjava.util.ArrayList;6 importjava.util.Arrays;7 importjava.util.Collections;8 importjava.util.Comparator;9 importjava.util.Date;10 importjava.util.HashMap;11 importjava.util.Hashtable;12 importjava.util.Iterator;13 importjava.util.List;14 importjava.util.Map;15 importjava.util.Random;16

17 importjavax.servlet.ServletContext;18 importjavax.servlet.ServletException;19 importjavax.servlet.ServletOutputStream;20 importjavax.servlet.http.HttpServletRequest;21 importjavax.servlet.http.HttpServletResponse;22

23 importorg.apache.commons.fileupload.FileItemFactory;24 importorg.apache.commons.fileupload.FileUploadException;25 importorg.apache.commons.fileupload.disk.DiskFileItemFactory;26 importorg.apache.commons.fileupload.servlet.ServletFileUpload;27 importorg.codehaus.jackson.map.ObjectMapper;28 importorg.springframework.stereotype.Controller;29 importorg.springframework.web.bind.annotation.RequestMapping;30 importorg.springframework.web.bind.annotation.RequestMethod;31 importorg.springframework.web.bind.annotation.ResponseBody;32 importorg.springframework.web.multipart.MultipartFile;33 importorg.springframework.web.multipart.MultipartHttpServletRequest;34

35 importcom.google.common.io.ByteStreams;36

37 @Controller38 @RequestMapping("kindeditor")39 public classKindEditorController {40

41 private static final ObjectMapper objectMapper = newObjectMapper();42

43 @RequestMapping(value = "/fileUpload", method =RequestMethod.POST)44 @ResponseBody45 public Map fileUpload(HttpServletRequest request,HttpServletResponse response) throwsServletException, IOException,46 FileUploadException {47 ServletContext application =request.getSession().getServletContext();48 String savePath = application.getRealPath("/") + "images/";49

50 //文件保存目录URL

51 String saveUrl = request.getContextPath() + "/images/";52

53 //定义允许上传的文件扩展名

54 HashMap extMap = new HashMap();55 extMap.put("image", "gif,jpg,jpeg,png,bmp");56 extMap.put("flash", "swf,flv");57 extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");58 extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");59

60 //最大文件大小

61 long maxSize = 1000000;62

63 response.setContentType("text/html; charset=UTF-8");64

65 if (!ServletFileUpload.isMultipartContent(request)) {66 return getError("请选择文件。");67 }68 //检查目录

69 File uploadDir = newFile(savePath);70 if (!uploadDir.isDirectory()) {71 return getError("上传目录不存在。");72 }73 //检查目录写权限

74 if (!uploadDir.canWrite()) {75 return getError("上传目录没有写权限。");76 }77

78 String dirName = request.getParameter("dir");79 if (dirName == null) {80 dirName = "image";81 }82 if (!extMap.containsKey(dirName)) {83 return getError("目录名不正确。");84 }85 //创建文件夹

86 savePath += dirName + "/";87 saveUrl += dirName + "/";88 File saveDirFile = newFile(savePath);89 if (!saveDirFile.exists()) {90 saveDirFile.mkdirs();91 }92 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");93 String ymd = sdf.format(newDate());94 savePath += ymd + "/";95 saveUrl += ymd + "/";96 File dirFile = newFile(savePath);97 if (!dirFile.exists()) {98 dirFile.mkdirs();99 }100

101 FileItemFactory factory = newDiskFileItemFactory();102 ServletFileUpload upload = newServletFileUpload(factory);103 upload.setHeaderEncoding("UTF-8");104

105

106 MultipartHttpServletRequest multipartRequest =(MultipartHttpServletRequest) request;107

108 Iterator item =multipartRequest.getFileNames();109 while(item.hasNext()) {110

111 String fileName =(String) item.next();112

113 MultipartFile file =multipartRequest.getFile(fileName);114

115

116 //检查文件大小

117

118 if (file.getSize() >maxSize) {119

120 return getError("上传文件大小超过限制。");121

122 }123

124 //检查扩展名

125

126 String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();127

128 if (!Arrays. asList(extMap.get(dirName).split(",")).contains(fileExt)) {129 return getError("上传文件扩展名是不允许的扩展名。\n只允许"

130 + extMap.get(dirName) + "格式。");131

132 }133 SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");134

135 String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." +fileExt;136

137 try{138

139 File uploadedFile = newFile(savePath, newFileName);140

141 ByteStreams.copy(file.getInputStream(), newFileOutputStream(uploadedFile));142

143 } catch(Exception e) {144

145 return getError("上传文件失败。");146

147 }148 Map msg = new HashMap();149 msg.put("error", 0);150 msg.put("url", saveUrl +newFileName);151 returnmsg;152 }153 return null;154 }155

156 private MapgetError(String message) {157 Map msg = new HashMap();158 msg.put("error", 1);159 msg.put("message", message);160 returnmsg;161 }162

163 @RequestMapping(value = "/fileManager", method =RequestMethod.POST)164 public voidfileManager(HttpServletRequest request,165 HttpServletResponse response) throwsServletException, IOException {166 ServletContext application =request.getSession().getServletContext();167 ServletOutputStream out =response.getOutputStream();168 //根目录路径,可以指定绝对路径,比如 /var/www/attached/

169 String rootPath = application.getRealPath("/") + "images/";170 //根目录URL,可以指定绝对路径,比如http://www.yoursite.com/attached/

171 String rootUrl = request.getContextPath() + "/images/";172 //图片扩展名

173 String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp"};174

175 String dirName = request.getParameter("dir");176 if (dirName != null) {177 if (!Arrays.asList(178 new String[] { "image", "flash", "media", "file"})179 .contains(dirName)) {180 out.println("Invalid Directory name.");181 return;182 }183 rootPath += dirName + "/";184 rootUrl += dirName + "/";185 File saveDirFile = newFile(rootPath);186 if (!saveDirFile.exists()) {187 saveDirFile.mkdirs();188 }189 }190 //根据path参数,设置各路径和URL

191 String path = request.getParameter("path") != null ?request192 .getParameter("path") : "";193 String currentPath = rootPath +path;194 String currentUrl = rootUrl +path;195 String currentDirPath =path;196 String moveupDirPath = "";197 if (!"".equals(path)) {198 String str = currentDirPath.substring(0,199 currentDirPath.length() - 1);200 moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0,201 str.lastIndexOf("/") + 1) : "";202 }203

204 //排序形式,name or size or type

205 String order = request.getParameter("order") != null ?request206 .getParameter("order").toLowerCase() : "name";207

208 //不允许使用..移动到上一级目录

209 if (path.indexOf("..") >= 0) {210 out.println("Access is not allowed.");211 return;212 }213 //最后一个字符不是/

214 if (!"".equals(path) && !path.endsWith("/")) {215 out.println("Parameter is not valid.");216 return;217 }218 //目录不存在或不是目录

219 File currentPathFile = newFile(currentPath);220 if (!currentPathFile.isDirectory()) {221 out.println("Directory does not exist.");222 return;223 }224 //遍历目录取的文件信息

225 List fileList = new ArrayList();226 if (currentPathFile.listFiles() != null) {227 for(File file : currentPathFile.listFiles()) {228 Hashtable hash = new Hashtable();229 String fileName =file.getName();230 if(file.isDirectory()) {231 hash.put("is_dir", true);232 hash.put("has_file", (file.listFiles() != null));233 hash.put("filesize", 0L);234 hash.put("is_photo", false);235 hash.put("filetype", "");236 } else if(file.isFile()) {237 String fileExt =fileName.substring(238 fileName.lastIndexOf(".") + 1).toLowerCase();239 hash.put("is_dir", false);240 hash.put("has_file", false);241 hash.put("filesize", file.length());242 hash.put("is_photo", Arrays.asList(fileTypes)243 .contains(fileExt));244 hash.put("filetype", fileExt);245 }246 hash.put("filename", fileName);247 hash.put("datetime",248 new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file249 .lastModified()));250 fileList.add(hash);251 }252 }253

254 if ("size".equals(order)) {255 Collections.sort(fileList, newSizeComparator());256 } else if ("type".equals(order)) {257 Collections.sort(fileList, newTypeComparator());258 } else{259 Collections.sort(fileList, newNameComparator());260 }261 Map msg = new HashMap();262 msg.put("moveup_dir_path", moveupDirPath);263 msg.put("current_dir_path", currentDirPath);264 msg.put("current_url", currentUrl);265 msg.put("total_count", fileList.size());266 msg.put("file_list", fileList);267 response.setContentType("application/json; charset=UTF-8");268 String msgStr =objectMapper.writeValueAsString(msg);269 out.println(msgStr);270 }271

272 class NameComparator implementsComparator {273 public intcompare(Object a, Object b) {274 Hashtable hashA =(Hashtable) a;275 Hashtable hashB =(Hashtable) b;276 if (((Boolean) hashA.get("is_dir"))277 && !((Boolean) hashB.get("is_dir"))) {278 return -1;279 } else if (!((Boolean) hashA.get("is_dir"))280 && ((Boolean) hashB.get("is_dir"))) {281 return 1;282 } else{283 return ((String) hashA.get("filename"))284 .compareTo((String) hashB.get("filename"));285 }286 }287 }288

289 class SizeComparator implementsComparator {290 public intcompare(Object a, Object b) {291 Hashtable hashA =(Hashtable) a;292 Hashtable hashB =(Hashtable) b;293 if (((Boolean) hashA.get("is_dir"))294 && !((Boolean) hashB.get("is_dir"))) {295 return -1;296 } else if (!((Boolean) hashA.get("is_dir"))297 && ((Boolean) hashB.get("is_dir"))) {298 return 1;299 } else{300 if (((Long) hashA.get("filesize")) >((Long) hashB301 .get("filesize"))) {302 return 1;303 } else if (((Long) hashA.get("filesize"))

313 class TypeComparator implementsComparator {314 public intcompare(Object a, Object b) {315 Hashtable hashA =(Hashtable) a;316 Hashtable hashB =(Hashtable) b;317 if (((Boolean) hashA.get("is_dir"))318 && !((Boolean) hashB.get("is_dir"))) {319 return -1;320 } else if (!((Boolean) hashA.get("is_dir"))321 && ((Boolean) hashB.get("is_dir"))) {322 return 1;323 } else{324 return ((String) hashA.get("filetype"))325 .compareTo((String) hashB.get("filetype"));326 }327 }328 }329

330 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值