List of usage examples for org.springframework.web.multipart.commons CommonsMultipartResolver CommonsMultipartResolver
public CommonsMultipartResolver(ServletContext servletContext)
From source file:org.openmrs.module.sync.web.CreateChildServlet.java
/** * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig) *///from w w w.j av a2s.co m @Override public void init(ServletConfig config) throws ServletException { // TODO Auto-generated method stub super.init(config); multipartResolver = new CommonsMultipartResolver(this.getServletContext()); }
From source file:com.qq.tars.web.controller.patch.UploadController.java
@RequestMapping(value = "server/api/upload_patch_package", produces = "application/json") @ResponseBody/*from w ww. j a v a 2 s . co m*/ public ServerPatchView upload(@Application @RequestParam String application, @ServerName @RequestParam("module_name") String moduleName, HttpServletRequest request, ModelMap modelMap) throws Exception { String comment = StringUtils.trimToEmpty(request.getParameter("comment")); String uploadTgzBasePath = systemConfigService.getUploadTgzPath(); CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver( request.getSession().getServletContext()); if (multipartResolver.isMultipart(request)) { MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; Iterator<String> it = multiRequest.getFileNames(); if (it.hasNext()) { MultipartFile file = multiRequest.getFile(it.next()); String originalName = file.getOriginalFilename(); String extension = FilenameUtils.getExtension(originalName); String temporary = uploadTgzBasePath + "/" + UUID.randomUUID() + "." + extension; IOUtils.copy(file.getInputStream(), new FileOutputStream(temporary)); String packageType = "suse"; // war? if (temporary.endsWith(".war")) { temporary = patchService.war2tgz(temporary, moduleName); } // ? String updateTgzPath = uploadTgzBasePath + "/" + application + "/" + moduleName; // ???? String uploadTgzName = application + "." + moduleName + "_" + packageType + "_" + System.currentTimeMillis() + ".tgz"; // ?? String uploadTgzFullPath = updateTgzPath + "/" + uploadTgzName; log.info("temporary path={}, upload path={}", temporary, uploadTgzFullPath); File uploadPathDir = new File(updateTgzPath); if (!uploadPathDir.exists()) { if (!uploadPathDir.mkdirs()) { throw new IOException( String.format("mkdirs error, path=%s", uploadPathDir.getCanonicalPath())); } } FileUtils.moveFile(new File(temporary), new File(uploadTgzFullPath)); return mapper.map(patchService.addServerPatch(application, moduleName, uploadTgzFullPath, comment), ServerPatchView.class); } } throw new Exception("???"); }
From source file:com.emaxcore.emaxdata.modules.testdrive.pub.web.TestdriveUploadSignatureController.java
/** * ???????//from w ww . j a v a 2 s . c o m * * @param model * @param request * @param response * @return * @throws Exception */ @RequestMapping(value = "uploadSignature") @ResponseBody public String uploadSignature(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws IOException { if (isDebugLogger) { logger.debug(" ??------uploadSignature-------start--------"); } response.setContentType(TestdrivePubConstant.ENCODED); Map<?, ?> jsonMap = null; // ? // ??????? StringBuilder idcardDriveProtocol = new StringBuilder(); // ??????? CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver( request.getSession().getServletContext()); if (multipartResolver.isMultipart(request)) { MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; // json String jsonDataStr = multiRequest.getParameter(TestdrivePubConstant.VALUE); if (Global.isSecretMode()) { if (isDebugLogger) { logger.debug("app ?---------- Start------{}---------", jsonDataStr); } AES256EncryptionUtils des = AES256EncryptionUtils.getInstance(); String jsonData = des.decrypt(jsonDataStr); jsonMap = JsonMapper.nonDefaultMapper().fromJson(jsonData, HashMap.class); } else { jsonMap = JsonMapper.nonDefaultMapper().fromJson(jsonDataStr, HashMap.class); } if (isDebugLogger) { logger.debug("uploadSignature?----------jsonMap---{}---------", jsonMap); } // ? TestDriveApplyInfo testDriveApplyInfo = new TestDriveApplyInfo(); //??-- String userFristName = TestdrivePubUtils.readJsonMapValue("fristName", jsonMap); if (StringUtils.isBlank(userFristName)) { jsonMap = this.saveJson(TestdrivePubConstant.ERROR_STATE, "fristName", ""); return TestdrivePubUtils.loggerJsonMap(jsonMap); } testDriveApplyInfo.setFirstName(userFristName); //??-- String userLastName = TestdrivePubUtils.readJsonMapValue("lastName", jsonMap); if (StringUtils.isBlank(userLastName)) { jsonMap = this.saveJson(TestdrivePubConstant.ERROR_STATE, "lastName", ""); return TestdrivePubUtils.loggerJsonMap(jsonMap); } testDriveApplyInfo.setLastName(userLastName); //?? String userName = userFristName + userLastName; testDriveApplyInfo.setName(userName); //telephone String telephone = TestdrivePubUtils.readJsonMapValue("telephone", jsonMap); if (StringUtils.isBlank(telephone)) { jsonMap = this.saveJson(TestdrivePubConstant.ERROR_STATE, "telephone", ""); return TestdrivePubUtils.loggerJsonMap(jsonMap); } testDriveApplyInfo.setMobile(telephone); //appellation String appellation = TestdrivePubUtils.readJsonMapValue("appellation", jsonMap); if (StringUtils.isBlank(appellation)) { jsonMap = this.saveJson(TestdrivePubConstant.ERROR_STATE, "appellation", ""); return TestdrivePubUtils.loggerJsonMap(jsonMap); } testDriveApplyInfo.setSex(appellation); //motorcycleType String motorcycleType = TestdrivePubUtils.readJsonMapValue("motorcycleType", jsonMap); if (StringUtils.isBlank(motorcycleType)) { jsonMap = this.saveJson(TestdrivePubConstant.ERROR_STATE, "motorcycleType", ""); return TestdrivePubUtils.loggerJsonMap(jsonMap); } testDriveApplyInfo.setVehiclesType(motorcycleType); // String widthName = TestdrivePubUtils.readJsonMapValue("userName", jsonMap); if (StringUtils.isBlank(widthName)) { jsonMap = this.saveJson(TestdrivePubConstant.ERROR_STATE, "userName", ""); return TestdrivePubUtils.loggerJsonMap(jsonMap); } testDriveApplyInfo.setWidthName(widthName); // ?MD5 String idCarMD5Hash = TestdrivePubUtils.readJsonMapValue("IDCarMD5Hash", jsonMap); // MD5 String driveMD5Hash = TestdrivePubUtils.readJsonMapValue("driveMD5Hash", jsonMap); // ????MD5 String protocolMD5Hash = TestdrivePubUtils.readJsonMapValue("protocolMD5Hash", jsonMap); // ??? String cidNumber = TestdrivePubUtils.readJsonMapValue("IDNumber", jsonMap); if (StringUtils.isBlank(cidNumber)) { jsonMap = this.saveJson(TestdrivePubConstant.ERROR_STATE, "???", ""); return TestdrivePubUtils.loggerJsonMap(jsonMap); } testDriveApplyInfo.setIdNumber(cidNumber); // ?D:\apache-tomcat-7.0.47\webapps\benz String path = TestdrivePubUtils.getRealPath(request); // ????/mnt/sdc1/data/benzsite String savePath = Global.getUserfilesBaseDir(); // ?/userfiles/app/login ??login String signaturePicAddressPre = TestdrivePubConstant.APP_USER_FILES_PATH + userName; String filePath = ""; // /benz String projectPath = request.getContextPath(); if (StringUtils.isBlank(savePath)) { // ?D:\apache-tomcat-7.0.47\webapps\benz/userfiles/app/login filePath = path + signaturePicAddressPre; } else { filePath = savePath + projectPath + signaturePicAddressPre; } Iterator<String> iter = multiRequest.getFileNames(); while (iter.hasNext()) { MultipartFile file = multiRequest.getFile((String) iter.next()); if (file != null && !file.isEmpty()) { String fileName = file.getOriginalFilename(); FileEmaxDataUtils.createDirectory(filePath); String fileNamePath = filePath + File.separator + fileName; String relativePath = projectPath + signaturePicAddressPre + File.separator + fileName; File localFile = new File(fileNamePath); file.transferTo(localFile); String md5Hash = MD5Utils.getFileMD5String(localFile); // ? if (fileName.startsWith(TestdrivePubConstant.IDCARD_PREFIX)) { if (!idCarMD5Hash.equals(md5Hash)) { idcardDriveProtocol.append(card); boolean deletFlag = localFile.delete(); if (deletFlag) { logger.info("??"); } } else { testDriveApplyInfo.setIdentityCardScanningFile(relativePath); } } // if (fileName.startsWith(TestdrivePubConstant.DRIVE_PREFIX)) { if (!driveMD5Hash.equals(md5Hash)) { idcardDriveProtocol.append(drive); boolean deletFlag = localFile.delete(); if (deletFlag) { logger.info("?!"); } } else { testDriveApplyInfo.setDriversLicenseScanningFile(relativePath); } } // ???? if (fileName.startsWith(TestdrivePubConstant.PROTOCOL_PREFIX)) { if (!protocolMD5Hash.equals(md5Hash)) { idcardDriveProtocol.append(protocol); boolean deletFlag = localFile.delete(); if (deletFlag) { logger.info("?????"); } } else { testDriveApplyInfo.setNumberSignature(relativePath); } } } } // ????1?1? String driveStatus = testDriveApplyInfo.getDriveStatus(); if ((StringUtils.isNotBlank(driveStatus) && (Integer.parseInt(driveStatus) < 1)) || StringUtils.isBlank(driveStatus)) { testDriveApplyInfo.setDriveStatus("1");// ?? } testDriveApplyInfoService.save(testDriveApplyInfo); } else { jsonMap = this.saveJson(TestdrivePubConstant.SUCCESS_STATE, "??", ""); return TestdrivePubUtils.loggerJsonMap(jsonMap); } if (StringUtils.isNotBlank(idcardDriveProtocol)) { jsonMap = this.saveJson(TestdrivePubConstant.ERROR_STATE, "", idcardDriveProtocol.toString()); return TestdrivePubUtils.loggerJsonMap(jsonMap); } else { jsonMap = this.saveJson(TestdrivePubConstant.SUCCESS_STATE, TestdrivePubConstant.SUCCESS, idcardDriveProtocol.toString()); } String appJson = TestdrivePubUtils.loggerJsonMap(jsonMap); if (isDebugLogger) { logger.debug("??--uploadSignature----end---"); } return appJson; }
From source file:io.pivotal.PaasappApplication.java
@RequestMapping("upload") public String uploadFiles(HttpServletRequest request) throws IllegalStateException, IOException { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver( request.getSession().getServletContext()); if (multipartResolver.isMultipart(request)) { MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; //?multiRequest ?? Iterator iter = multiRequest.getFileNames(); while (iter.hasNext()) { //??//from ww w.j ava2s . c o m MultipartFile file = multiRequest.getFile(iter.next().toString()); if (file != null) { String path = file.getOriginalFilename(); // file.transferTo(new File(path)); } } } return "/success"; }
From source file:cn.mk.ndms.modules.lease.web.controller.LeaseController.java
@RequestMapping(value = "upload", method = RequestMethod.POST) @ResponseBody// ww w.j a v a 2 s. c om public AjaxBean upload(HttpServletRequest request, HttpServletResponse response) throws IOException { try { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver( request.getSession().getServletContext()); if (multipartResolver.isMultipart(request)) { MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; Iterator<String> iter = multiRequest.getFileNames(); while (iter.hasNext()) { MultipartFile file = multiRequest.getFile((String) iter.next()); if (file != null) { String fileName = file.getOriginalFilename(); String path1 = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "file" + File.separator; // ??? String path2 = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + fileName; String path = path1 + path2; File localFile = new File(path); file.transferTo(localFile); Lease lease = leaseService.findOne(request.getParameter("id")); lease.setFilePath(path2); leaseService.update(lease); } } } return AjaxBean.getInstance("success"); } catch (Exception ex) { return AjaxBean.getInstance("error", ex.getMessage()); } }
From source file:com.daoke.mobileserver.user.controller.UserController.java
/** * ?/*w w w.ja v a 2 s . c o m*/ * * @param appKey * @param accountID * @param request * @return */ @RequestMapping("/uploadHeadImage") public @ResponseBody CommonJsonResult uploadImage(@RequestParam String appKey, @RequestParam String accountID, HttpServletRequest request) { CommonJsonResult res = new CommonJsonResult(); String appkey = ConstantsUtil.getAppKey(appKey); String secret = ConstantsUtil.getSecret(appKey); String headImageUrl = ""; try { //url CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver( request.getSession().getServletContext()); if (multipartResolver.isMultipart(request)) { MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; Iterator<String> iter = multiRequest.getFileNames(); while (iter.hasNext()) { MultipartFile file = multiRequest.getFile(iter.next()); String fileResultUrl = customService.saveFile(appkey, secret, file, saveFile); CommonJsonResult fileResult = (CommonJsonResult) JsonMapper.fromJson(fileResultUrl, CommonJsonResult.class); Map<String, String> param = (Map<String, String>) fileResult.getRESULT(); headImageUrl = param.get("url"); break; } } if (headImageUrl != null) { if (userGradeService.uploadHeadImage(accountID, headImageUrl) > 0) { res.setERRORCODE(ConstantsUtil.ERRORCODE_OK); Map<String, String> map = new HashMap<String, String>(); map.put("headImageUrl", headImageUrl); res.setRESULT(map); } else { res.setERRORCODE(ConstantsUtil.ERRORCODE_SERVICE_ERROR); res.setRESULT("?"); } } } catch (Exception e1) { e1.printStackTrace(); logger.error("?:" + e1.getMessage()); res.setERRORCODE(ConstantsUtil.ERRORCODE_SERVICE_ERROR); res.setRESULT("?"); } return res; }
From source file:org.springframework.web.multipart.commons.CommonsMultipartResolverTests.java
@Test public void withServletContextAndFilter() throws Exception { StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(new MockServletContext()); wac.registerSingleton("filterMultipartResolver", MockCommonsMultipartResolver.class, new MutablePropertyValues()); wac.getServletContext().setAttribute(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, new File("mytemp")); wac.refresh();/*w w w.j av a 2 s . c o m*/ wac.getServletContext().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); CommonsMultipartResolver resolver = new CommonsMultipartResolver(wac.getServletContext()); assertTrue(resolver.getFileItemFactory().getRepository().getAbsolutePath().endsWith("mytemp")); MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter"); filterConfig.addInitParameter("class", "notWritable"); filterConfig.addInitParameter("unknownParam", "someValue"); final MultipartFilter filter = new MultipartFilter(); filter.init(filterConfig); final List<MultipartFile> files = new ArrayList<>(); final FilterChain filterChain = new FilterChain() { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) { MultipartHttpServletRequest request = (MultipartHttpServletRequest) servletRequest; files.addAll(request.getFileMap().values()); } }; FilterChain filterChain2 = new PassThroughFilterChain(filter, filterChain); MockHttpServletRequest originalRequest = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); originalRequest.setMethod("POST"); originalRequest.setContentType("multipart/form-data"); originalRequest.addHeader("Content-type", "multipart/form-data"); filter.doFilter(originalRequest, response, filterChain2); CommonsMultipartFile file1 = (CommonsMultipartFile) files.get(0); CommonsMultipartFile file2 = (CommonsMultipartFile) files.get(1); assertTrue(((MockFileItem) file1.getFileItem()).deleted); assertTrue(((MockFileItem) file2.getFileItem()).deleted); }
From source file:org.springframework.web.multipart.commons.CommonsMultipartResolverTests.java
@Test public void withServletContextAndFilterWithCustomBeanName() throws Exception { StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(new MockServletContext()); wac.refresh();/*w ww. j a v a 2 s .co m*/ wac.registerSingleton("myMultipartResolver", MockCommonsMultipartResolver.class, new MutablePropertyValues()); wac.getServletContext().setAttribute(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, new File("mytemp")); wac.getServletContext().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); CommonsMultipartResolver resolver = new CommonsMultipartResolver(wac.getServletContext()); assertTrue(resolver.getFileItemFactory().getRepository().getAbsolutePath().endsWith("mytemp")); MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter"); filterConfig.addInitParameter("multipartResolverBeanName", "myMultipartResolver"); final List<MultipartFile> files = new ArrayList<>(); FilterChain filterChain = new FilterChain() { @Override public void doFilter(ServletRequest originalRequest, ServletResponse response) { if (originalRequest instanceof MultipartHttpServletRequest) { MultipartHttpServletRequest request = (MultipartHttpServletRequest) originalRequest; files.addAll(request.getFileMap().values()); } } }; MultipartFilter filter = new MultipartFilter() { private boolean invoked = false; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { super.doFilterInternal(request, response, filterChain); super.doFilterInternal(request, response, filterChain); if (invoked) { throw new ServletException("Should not have been invoked twice"); } invoked = true; } }; filter.init(filterConfig); MockHttpServletRequest originalRequest = new MockHttpServletRequest(); originalRequest.setMethod("POST"); originalRequest.setContentType("multipart/form-data"); originalRequest.addHeader("Content-type", "multipart/form-data"); HttpServletResponse response = new MockHttpServletResponse(); filter.doFilter(originalRequest, response, filterChain); CommonsMultipartFile file1 = (CommonsMultipartFile) files.get(0); CommonsMultipartFile file2 = (CommonsMultipartFile) files.get(1); assertTrue(((MockFileItem) file1.getFileItem()).deleted); assertTrue(((MockFileItem) file2.getFileItem()).deleted); }