@RequestMapping(value = WebUrlConstant.UPLOADFILE) @ResponseBody public Map<String, Object> uploadFile(HttpServletRequest request,HttpServletResponse httpresponse) { try { // 转型为MultipartHttpRequest MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; // 根据前台的name名称得到上传的文件 MultipartFile file = multipartRequest.getFile("upfile"); if(!file.isEmpty()){ boolean fileFlag = true; if(file.getSize()>1024*1024*10){ jsonMap.put("flag", RESPONSE_FAIL); jsonMap.put("message", "上传文件大小超过10M"); return jsonMap; } // 获得文件名: String realFileName = file.getOriginalFilename(); // 截取文件后缀名 String fuffix = realFileName.substring(realFileName .lastIndexOf(".")); if (!(".jpg".equals(StringUtils.lowerCase(fuffix)) || ".png".equals(StringUtils.lowerCase(fuffix)) || ".pdf".equals(StringUtils.lowerCase(fuffix)) || ".doc".equals(StringUtils.lowerCase(fuffix)) || ".docx".equals(StringUtils.lowerCase(fuffix)))) { jsonMap.put("flag", RESPONSE_FAIL); jsonMap.put("message", "文件不是JPG/PNG/PDF/DOC/DOCX格式"); return jsonMap; } // 获取路径 String ctxPath = PropertiesUtils.getValue("filePath"); // 创建文件 File dirPath = new File(ctxPath); if (!dirPath.exists()) { dirPath.mkdirs(); } File uploadFile = new File(ctxPath + File.separatorChar + realFileName); FileCopyUtils.copy(file.getBytes(), uploadFile); jsonMap.put("fileName", realFileName); } jsonMap.put( "flag", getFlag() ); jsonMap.put( "message", getMessage() ); } catch (Exception e) { log.error(e.getMessage(), e); } return jsonMap; }
<!-- 文件上传 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" > <property name="maxUploadSize"> <value>104857600</value> </property> <property name="maxInMemorySize"> <value>4096</value> </property> </bean>