List of usage examples for org.springframework.web.multipart.commons CommonsMultipartFile getInputStream
@Override public InputStream getInputStream() throws IOException
From source file:com.amediamanager.dao.DynamoDbUserDaoImpl.java
/** * Upload the profile pic to S3 and return it's URL * @param profilePic//from w ww . j a va 2s .com * @return The fully-qualified URL of the photo in S3 * @throws IOException */ public String uploadFileToS3(CommonsMultipartFile profilePic) throws IOException { // Profile pic prefix String prefix = config.getProperty(ConfigProps.S3_PROFILE_PIC_PREFIX); // Date string String dateString = new SimpleDateFormat("ddMMyyyy").format(new java.util.Date()); String s3Key = prefix + "/" + dateString + "/" + UUID.randomUUID().toString() + "_" + profilePic.getOriginalFilename(); // Get bucket String s3bucket = config.getProperty(ConfigProps.S3_UPLOAD_BUCKET); // Create a ObjectMetadata instance to set the ACL, content type and length ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentType(profilePic.getContentType()); metadata.setContentLength(profilePic.getSize()); // Create a PutRequest to upload the image PutObjectRequest putObject = new PutObjectRequest(s3bucket, s3Key, profilePic.getInputStream(), metadata); // Put the image into S3 s3Client.putObject(putObject); s3Client.setObjectAcl(s3bucket, s3Key, CannedAccessControlList.PublicRead); return "http://" + s3bucket + ".s3.amazonaws.com/" + s3Key; }
From source file:com.jeans.iservlet.controller.impl.ImportController.java
@RequestMapping(method = RequestMethod.POST, value = "/hr") @ResponseBody/*from w ww . j av a2s. c om*/ public void importHR(@RequestParam("data") CommonsMultipartFile data, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); if (null == data) { showError(out, "??"); out.close(); return; } int deptCount = 0, emplCount = 0; String info = null; try (Workbook workBook = WorkbookFactory.create(data.getInputStream())) { Sheet deptSheet = workBook.getSheet(""); Sheet emplSheet = workBook.getSheet(""); if (null == deptSheet || null == emplSheet) { data.getInputStream().close(); showError(out, "????Sheet"); out.close(); return; } Company comp = getCurrentCompany(); // deptSheet: 1?04?5?????? int total = deptSheet.getLastRowNum() + emplSheet.getLastRowNum(); double progress = 0.0; double step = 100.0 / (double) total; showProgressDialog(out, getCurrentCompany().getAlias() + ""); int last = deptSheet.getLastRowNum(); for (int rn = 1; rn <= last; rn++) { Row r = deptSheet.getRow(rn); // ??""??? String flag = StringUtils .trim(ExcelUtils.getCellValueAsString(r.getCell(4, Row.RETURN_BLANK_AS_NULL))); progress += step; if (!"".equals(flag)) { continue; } // ?name? String name = ExcelUtils.getCellValueAsString(r.getCell(0, Row.RETURN_BLANK_AS_NULL)); if (StringUtils.isBlank(name)) { continue; } else { name = StringUtils.trim(name); } showProgress(out, "" + name, progress);// // ?alias? String alias = ExcelUtils.getCellValueAsString(r.getCell(1, Row.RETURN_BLANK_AS_NULL)); if (StringUtils.isBlank(alias)) { alias = name.substring(0, 15); } else { alias = StringUtils.trim(alias); } // ?ID(superiorId)???????? String superior = ExcelUtils.getCellValueAsString(r.getCell(2, Row.RETURN_BLANK_AS_NULL)); long superiorId = 0; if (StringUtils.isBlank(superior)) { superiorId = comp.getId(); } else { Department suprDept = hrService.findDepartmentByName(comp, superior); if (null == suprDept) { continue; } else { superiorId = suprDept.getId(); } } // ???listOrder??short999??1999 short listOrder = 999; try { double order = (double) ExcelUtils.getCellValue(r.getCell(3, Row.RETURN_BLANK_AS_NULL)); if (order < 1) { listOrder = 1; } else if (order > 999) { listOrder = 999; } else { listOrder = (short) Math.round(order); } } catch (ClassCastException e) { log(e); listOrder = 999; } if (null != hrService.createDept(name, alias, superiorId, listOrder)) { deptCount++; } } // emplSheet: 1?08?9??????????????admin? last = emplSheet.getLastRowNum(); for (int rn = 1; rn <= last; rn++) { Row r = emplSheet.getRow(rn); // ??""??? String flag = StringUtils .trim(ExcelUtils.getCellValueAsString(r.getCell(8, Row.RETURN_BLANK_AS_NULL))); progress += step; if (!"".equals(flag)) { continue; } // ???name? String name = ExcelUtils.getCellValueAsString(r.getCell(0, Row.RETURN_BLANK_AS_NULL)); if (StringUtils.isBlank(name)) { continue; } else { name = StringUtils.trim(name); } showProgress(out, "" + name, progress); // // ?ID(deptId)??? String deptName = ExcelUtils.getCellValueAsString(r.getCell(1, Row.RETURN_BLANK_AS_NULL)); long deptId = 0; if (StringUtils.isBlank(deptName)) { continue; } else { Department dept = hrService.findDepartmentByName(comp, deptName); if (null == dept) { continue; } else { deptId = dept.getId(); } } // ???listOrder??short999??1999 short listOrder = 999; try { double order = (double) ExcelUtils.getCellValue(r.getCell(2, Row.RETURN_BLANK_AS_NULL)); if (order < 1) { listOrder = 1; } else if (order > 999) { listOrder = 999; } else { listOrder = (short) Math.round(order); } } catch (ClassCastException e) { log(e); listOrder = 999; } // ???????admin? boolean leader = "".equals( StringUtils.trim(ExcelUtils.getCellValueAsString(r.getCell(3, Row.RETURN_BLANK_AS_NULL)))); boolean supervisor = "".equals( StringUtils.trim(ExcelUtils.getCellValueAsString(r.getCell(4, Row.RETURN_BLANK_AS_NULL)))); boolean auditor = "".equals( StringUtils.trim(ExcelUtils.getCellValueAsString(r.getCell(5, Row.RETURN_BLANK_AS_NULL)))); boolean iter = "".equals( StringUtils.trim(ExcelUtils.getCellValueAsString(r.getCell(6, Row.RETURN_BLANK_AS_NULL)))); boolean admin = "".equals( StringUtils.trim(ExcelUtils.getCellValueAsString(r.getCell(7, Row.RETURN_BLANK_AS_NULL)))); if (null != hrService.createEmpl(name, deptId, listOrder, leader, supervisor, auditor, iter, admin)) { emplCount++; } } info = "?" + deptCount + "" + emplCount + "??"; } catch (Exception e) { log(e); info = "????" + deptCount + "" + emplCount + "??"; } finally { data.getInputStream().close(); closeProgressDialog(out); showInfo(out, info); out.close(); log(info); } }
From source file:com.jeans.iservlet.controller.impl.ImportController.java
@RequestMapping(method = RequestMethod.POST, value = "/ci") @ResponseBody/*from ww w. ja v a2s . c o m*/ public void importCI(@RequestParam("data") CommonsMultipartFile data, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); if (null == data) { showError(out, "??"); out.close(); return; } int hardCount = 0, softCount = 0; String info = null; try (Workbook workBook = WorkbookFactory.create(data.getInputStream())) { Sheet hardSheet = workBook.getSheet(""); Sheet softSheet = workBook.getSheet(""); if (null == hardSheet || null == softSheet) { data.getInputStream().close(); showError(out, "????Sheet"); out.close(); return; } Company comp = getCurrentCompany(); ExcelUtils.setNumberFormat("#"); SimpleDateFormat sdf = new SimpleDateFormat("yyyymm"); int total = hardSheet.getLastRowNum() + softSheet.getLastRowNum(); double progress = 0.0; double step = 100.0 / (double) total; showProgressDialog(out, getCurrentCompany().getAlias() + "?"); // hardSheet: 1?019?200? int last = hardSheet.getLastRowNum(); for (int rn = 1; rn <= last; rn++) { Row r = hardSheet.getRow(rn); // ??""??? String flag = StringUtils .trim(ExcelUtils.getCellValueAsString(r.getCell(0, Row.RETURN_BLANK_AS_NULL))); // ???name? String name = StringUtils .trim(ExcelUtils.getCellValueAsString(r.getCell(4, Row.RETURN_BLANK_AS_NULL))); progress += step; if (!"".equals(flag) || StringUtils.isBlank(name)) { continue; } showProgress(out, "" + name, progress); // Map<String, Object> hardware = new HashMap<String, Object>(); hardware.put("company", comp); hardware.put("type", AssetConstants.HARDWARE_ASSET); hardware.put("name", name); hardware.put("code", StringUtils.trim(ExcelUtils.getCellValueAsString(r.getCell(1, Row.RETURN_BLANK_AS_NULL)))); hardware.put("financialCode", StringUtils.trim(ExcelUtils.getCellValueAsString(r.getCell(2, Row.RETURN_BLANK_AS_NULL)))); hardware.put("catalog", parseAssetCatalog( StringUtils.trim( ExcelUtils.getCellValueAsString(r.getCell(3, Row.RETURN_BLANK_AS_NULL))), AssetConstants.HARDWARE_ASSET)); hardware.put("vendor", StringUtils.trim(ExcelUtils.getCellValueAsString(r.getCell(5, Row.RETURN_BLANK_AS_NULL)))); hardware.put("modelOrVersion", StringUtils.trim(ExcelUtils.getCellValueAsString(r.getCell(6, Row.RETURN_BLANK_AS_NULL)))); hardware.put("assetUsage", StringUtils.trim(ExcelUtils.getCellValueAsString(r.getCell(7, Row.RETURN_BLANK_AS_NULL)))); hardware.put("sn", StringUtils.trim(ExcelUtils.getCellValueAsString(r.getCell(8, Row.RETURN_BLANK_AS_NULL)))); hardware.put("configuration", StringUtils.trim(ExcelUtils.getCellValueAsString(r.getCell(9, Row.RETURN_BLANK_AS_NULL)))); hardware.put("purchaseTime", ExcelUtils.getCellValueAsDate(r.getCell(10, Row.RETURN_BLANK_AS_NULL), sdf)); try { double q = (double) ExcelUtils.getCellValue(r.getCell(11, Row.RETURN_BLANK_AS_NULL)); if (q < 1) { hardware.put("quantity", 1); } else { hardware.put("quantity", (int) Math.round(q)); } } catch (Exception e) { hardware.put("quantity", 1); } try { hardware.put("cost", BigDecimal .valueOf((double) ExcelUtils.getCellValue(r.getCell(12, Row.RETURN_BLANK_AS_NULL)))); } catch (Exception e) { hardware.put("cost", new BigDecimal(0)); } hardware.put("state", parseAssetState( StringUtils.trim( ExcelUtils.getCellValueAsString(r.getCell(13, Row.RETURN_BLANK_AS_NULL))), AssetConstants.HARDWARE_ASSET)); hardware.put("warranty", parseHardwareWarranty(StringUtils .trim(ExcelUtils.getCellValueAsString(r.getCell(14, Row.RETURN_BLANK_AS_NULL))))); hardware.put("location", StringUtils.trim(ExcelUtils.getCellValueAsString(r.getCell(15, Row.RETURN_BLANK_AS_NULL)))); hardware.put("ip", StringUtils.trim(ExcelUtils.getCellValueAsString(r.getCell(16, Row.RETURN_BLANK_AS_NULL)))); hardware.put("importance", parseHardwareImportance(StringUtils .trim(ExcelUtils.getCellValueAsString(r.getCell(17, Row.RETURN_BLANK_AS_NULL))))); hardware.put("owner", hrService.findEmployeeByName(getCurrentCompany(), StringUtils .trim(ExcelUtils.getCellValueAsString(r.getCell(18, Row.RETURN_BLANK_AS_NULL))))); hardware.put("comment", StringUtils.trim(ExcelUtils.getCellValueAsString(r.getCell(19, Row.RETURN_BLANK_AS_NULL)))); if (null != assetService.create(hardware)) { hardCount++; } } // softSheet: 1?013?140? last = softSheet.getLastRowNum(); for (int rn = 1; rn <= last; rn++) { Row r = softSheet.getRow(rn); // ??""??? String flag = StringUtils .trim(ExcelUtils.getCellValueAsString(r.getCell(0, Row.RETURN_BLANK_AS_NULL))); // ???name? String name = StringUtils .trim(ExcelUtils.getCellValueAsString(r.getCell(2, Row.RETURN_BLANK_AS_NULL))); progress += step; if (!"".equals(flag) || StringUtils.isBlank(name)) { continue; } showProgress(out, "" + name, progress); // Map<String, Object> software = new HashMap<String, Object>(); software.put("company", comp); software.put("type", AssetConstants.SOFTWARE_ASSET); software.put("name", name); software.put("catalog", parseAssetCatalog( StringUtils.trim( ExcelUtils.getCellValueAsString(r.getCell(1, Row.RETURN_BLANK_AS_NULL))), AssetConstants.SOFTWARE_ASSET)); software.put("vendor", StringUtils.trim(ExcelUtils.getCellValueAsString(r.getCell(3, Row.RETURN_BLANK_AS_NULL)))); software.put("modelOrVersion", StringUtils.trim(ExcelUtils.getCellValueAsString(r.getCell(4, Row.RETURN_BLANK_AS_NULL)))); software.put("assetUsage", StringUtils.trim(ExcelUtils.getCellValueAsString(r.getCell(5, Row.RETURN_BLANK_AS_NULL)))); software.put("purchaseTime", ExcelUtils.getCellValueAsDate(r.getCell(6, Row.RETURN_BLANK_AS_NULL), sdf)); try { double q = (double) ExcelUtils.getCellValue(r.getCell(7, Row.RETURN_BLANK_AS_NULL)); if (q < 1) { software.put("quantity", 1); } else { software.put("quantity", (int) Math.round(q)); } } catch (Exception e) { software.put("quantity", 1); } try { software.put("cost", BigDecimal .valueOf((double) ExcelUtils.getCellValue(r.getCell(8, Row.RETURN_BLANK_AS_NULL)))); } catch (Exception e) { software.put("cost", new BigDecimal(0)); } software.put("state", parseAssetState( StringUtils.trim( ExcelUtils.getCellValueAsString(r.getCell(9, Row.RETURN_BLANK_AS_NULL))), AssetConstants.SOFTWARE_ASSET)); software.put("softwareType", parseSoftwareType(StringUtils .trim(ExcelUtils.getCellValueAsString(r.getCell(10, Row.RETURN_BLANK_AS_NULL))))); software.put("license", StringUtils.trim(ExcelUtils.getCellValueAsString(r.getCell(11, Row.RETURN_BLANK_AS_NULL)))); software.put("expiredTime", ExcelUtils.getCellValueAsDate(r.getCell(12, Row.RETURN_BLANK_AS_NULL), sdf)); software.put("comment", StringUtils.trim(ExcelUtils.getCellValueAsString(r.getCell(13, Row.RETURN_BLANK_AS_NULL)))); if (null != assetService.create(software)) { softCount++; } } info = "??" + hardCount + "" + softCount + ""; } catch (Exception e) { log(e); info = "?????" + hardCount + "" + softCount + ""; } finally { data.getInputStream().close(); closeProgressDialog(out); showInfo(out, info); out.close(); log(info); } }
From source file:com.gbcom.system.controller.SysInfoController.java
/** * ?/*from w ww . j ava 2s.c om*/ * * @param request * HttpServletRequest * @param uploadFile * CommonsMultipartFile * @param response * HttpServletResponse */ @RequestMapping public void recovery(HttpServletRequest request, @RequestParam(value = "upFile", required = true) CommonsMultipartFile uploadFile, HttpServletResponse response) { String fileName = uploadFile.getOriginalFilename(); try { if (fileName == null || fileName.trim().equals("")) { sendFailureJSON(response, "????"); return; } String fileIp = fileName.substring(fileName.indexOf("-") + 1, fileName.lastIndexOf("-")); LinkedHashMap<String, String> ipMap = CmUtil.getLocalAddress(); if (!ipMap.containsKey(fileIp)) { sendFailureJSON(response, "????!"); return; } } catch (Exception e1) { sendFailureJSON(response, "????!"); return; } String realPath = request.getSession().getServletContext().getRealPath("/upload"); boolean isSuccess = false; File file = new File(realPath, fileName); try { FileUtils.copyInputStreamToFile(uploadFile.getInputStream(), file); String filePath = realPath + File.separator + uploadFile.getOriginalFilename(); // ? final SqlImportManager sqlService = new SqlImportManager(); isSuccess = sqlService.importSql(filePath); } catch (Exception e) { super.processException(response, e); } finally { try { file.delete(); } catch (Exception e) { } } if (!isSuccess) { sendFailureJSON(response, "?"); } else { sendSuccessJSON(response, "??"); } }
From source file:org.asqatasun.webapp.validator.AddScenarioFormValidator.java
/** * /*from www.j ava 2 s .c o m*/ * @param addScenarioCommand * @param errors * @return whether the scenario handled by the current AddScenarioCommand * has a correct type and size */ public boolean checkScenarioFileTypeAndSize(AddScenarioCommand addScenarioCommand, Errors errors) { if (addScenarioCommand.getScenarioFile() == null) { // if no file uploaded LOGGER.debug("empty Scenario File"); errors.rejectValue(GENERAL_ERROR_MSG_KEY, MANDATORY_FIELD_MSG_BUNDLE_KEY); errors.rejectValue(SCENARIO_FILE_KEY, NO_SCENARIO_UPLOADED_MSG_BUNDLE_KEY); return false; } Metadata metadata = new Metadata(); MimeTypes mimeTypes = TikaConfig.getDefaultConfig().getMimeRepository(); String mime; try { CommonsMultipartFile cmf = addScenarioCommand.getScenarioFile(); if (cmf.getSize() > maxFileSize) { Long maxFileSizeInMega = maxFileSize / 1000000; String[] arg = { maxFileSizeInMega.toString() }; errors.rejectValue(GENERAL_ERROR_MSG_KEY, MANDATORY_FIELD_MSG_BUNDLE_KEY); errors.rejectValue(SCENARIO_FILE_KEY, FILE_SIZE_EXCEEDED_MSG_BUNDLE_KEY, arg, "{0}"); return false; } else if (cmf.getSize() > 0) { mime = mimeTypes.detect(new BufferedInputStream(cmf.getInputStream()), metadata).toString(); LOGGER.debug("mime " + mime + " " + cmf.getOriginalFilename()); if (!authorizedMimeType.contains(mime)) { errors.rejectValue(GENERAL_ERROR_MSG_KEY, MANDATORY_FIELD_MSG_BUNDLE_KEY); errors.rejectValue(SCENARIO_FILE_KEY, NOT_SCENARIO_MSG_BUNDLE_KEY); return false; } } else { LOGGER.debug("File with size null"); errors.rejectValue(GENERAL_ERROR_MSG_KEY, MANDATORY_FIELD_MSG_BUNDLE_KEY); errors.rejectValue(SCENARIO_FILE_KEY, NO_SCENARIO_UPLOADED_MSG_BUNDLE_KEY); return false; } } catch (IOException ex) { LOGGER.warn(ex); errors.rejectValue(SCENARIO_FILE_KEY, NOT_SCENARIO_MSG_BUNDLE_KEY); errors.rejectValue(GENERAL_ERROR_MSG_KEY, MANDATORY_FIELD_MSG_BUNDLE_KEY); return false; } return true; }
From source file:org.springframework.web.multipart.commons.CommonsMultipartResolverTests.java
private void doTestFiles(MultipartHttpServletRequest request) throws IOException { Set<String> fileNames = new HashSet<>(); Iterator<String> fileIter = request.getFileNames(); while (fileIter.hasNext()) { fileNames.add(fileIter.next());//from www. ja v a 2 s .c o m } assertEquals(3, fileNames.size()); assertTrue(fileNames.contains("field1")); assertTrue(fileNames.contains("field2")); assertTrue(fileNames.contains("field2x")); CommonsMultipartFile file1 = (CommonsMultipartFile) request.getFile("field1"); CommonsMultipartFile file2 = (CommonsMultipartFile) request.getFile("field2"); CommonsMultipartFile file2x = (CommonsMultipartFile) request.getFile("field2x"); Map<String, MultipartFile> fileMap = request.getFileMap(); assertEquals(3, fileMap.size()); assertTrue(fileMap.containsKey("field1")); assertTrue(fileMap.containsKey("field2")); assertTrue(fileMap.containsKey("field2x")); assertEquals(file1, fileMap.get("field1")); assertEquals(file2, fileMap.get("field2")); assertEquals(file2x, fileMap.get("field2x")); MultiValueMap<String, MultipartFile> multiFileMap = request.getMultiFileMap(); assertEquals(3, multiFileMap.size()); assertTrue(multiFileMap.containsKey("field1")); assertTrue(multiFileMap.containsKey("field2")); assertTrue(multiFileMap.containsKey("field2x")); List<MultipartFile> field1Files = multiFileMap.get("field1"); assertEquals(2, field1Files.size()); assertTrue(field1Files.contains(file1)); assertEquals(file1, multiFileMap.getFirst("field1")); assertEquals(file2, multiFileMap.getFirst("field2")); assertEquals(file2x, multiFileMap.getFirst("field2x")); assertEquals("type1", file1.getContentType()); assertEquals("type2", file2.getContentType()); assertEquals("type2", file2x.getContentType()); assertEquals("field1.txt", file1.getOriginalFilename()); assertEquals("field2.txt", file2.getOriginalFilename()); assertEquals("field2x.txt", file2x.getOriginalFilename()); assertEquals("text1", new String(file1.getBytes())); assertEquals("text2", new String(file2.getBytes())); assertEquals(5, file1.getSize()); assertEquals(5, file2.getSize()); assertTrue(file1.getInputStream() instanceof ByteArrayInputStream); assertTrue(file2.getInputStream() instanceof ByteArrayInputStream); File transfer1 = new File("C:/transfer1"); file1.transferTo(transfer1); File transfer2 = new File("C:/transfer2"); file2.transferTo(transfer2); assertEquals(transfer1, ((MockFileItem) file1.getFileItem()).writtenFile); assertEquals(transfer2, ((MockFileItem) file2.getFileItem()).writtenFile); }