@RequestMapping(value = "oneFileUpload", method = RequestMethod.POST) public String uploadLoginSplash(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException { if (!file.isEmpty()) { String realPath = request.getSession().getServletContext().getRealPath(SPLASH); // 这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉,我是看它的源码才知道的 FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, SPLASH_JPG)); } return "manager/setting/settingManager"; }
@RequestMapping("/idCardImageUpload") public void idCardImageUpload(HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException { // 创建一个通用的多部分解析器 CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver( request.getSession().getServletContext()); String finalFileName=""; // 判断 request 是否有文件上传,即多部分请求 if (multipartResolver.isMultipart(request)) { // 转换成多部分request MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; // 取得request中的所有文件名 Iterator<String> iter = multiRequest.getFileNames(); while (iter.hasNext()) { // 取得上传文件 MultipartFile file = multiRequest.getFile(iter.next()); if (file != null) { // 取得当前上传文件的文件名称 String fileName = file.getOriginalFilename(); // 如果名称不为“”,说明该文件存在,否则说明该文件不存在 if (StringUtils.isNotEmpty(fileName)) { String[] strs = fileName.split("\\."); String fileExtention="png"; // 重命名上传后的文件名 if(strs.length >=2){ fileExtention=strs[strs.length-1]; } try { fileName = AES.Encrypt(fileName, DateFormatUtil .format(new Date(), "yyyyMMddHHmmssSSS") .substring(1))+"."+fileExtention; finalFileName +=fileName+","; // 定义上传路径 String imagePath = (String) BasePropertyConfigurer .getContextProperty("idCardImageUploadPath"); String path = imagePath + fileName; File localFile = new File(path); file.transferTo(localFile); } catch (Exception e) { e.printStackTrace(); } } } } JSONObject jsonObj = new JSONObject(); response.setContentType("text/html;charset=UTF-8"); jsonObj.put("success", true); jsonObj.put("fileName",finalFileName); returnJsonObject(response, jsonObj); } }
原文地址:http://blog.csdn.net/fansunion/article/details/42746405