List of usage examples for org.springframework.web.multipart MultipartFile getInputStream
@Override
InputStream getInputStream() throws IOException;
From source file:business.Reciept.java
private static model.Image createImage(MultipartFile multiPartFile) throws Exception { byte[] byteArray = multiPartFile.getBytes(); BufferedImage image = ImageIO.read(multiPartFile.getInputStream()); int height = image.getHeight(); int width = image.getWidth(); return new model.Image(byteArray, multiPartFile.getContentType(), height, width); }
From source file:nu.yona.server.subscriptions.rest.UserPhotoController.java
private static byte[] getPngBytes(MultipartFile file) { try (InputStream inStream = file.getInputStream()) { BufferedImage image = ImageIO.read(inStream); if (image == null) { throw InvalidDataException.unsupportedPhotoFileType(); }// ww w. java 2 s . c om ByteArrayOutputStream pngBytes = new ByteArrayOutputStream(); ImageIO.write(image, "png", pngBytes); return pngBytes.toByteArray(); } catch (IOException e) { throw YonaException.unexpected(e); } }
From source file:org.wallride.support.ExtendedResourceUtils.java
public static void write(Resource resource, MultipartFile file) throws IOException { if (resource instanceof WritableResource) { // IOUtils.copy(file.getInputStream(), ((WritableResource) resource).getOutputStream()); try (InputStream input = file.getInputStream(); OutputStream output = ((WritableResource) resource).getOutputStream()) { IOUtils.copy(input, output); }// w w w.j ava 2 s .co m return; } FileUtils.copyInputStreamToFile(file.getInputStream(), getFile(resource.getURI())); }
From source file:com.beginner.core.utils.FileUpload.java
/** * //from www.j a va 2 s . c o m * @param file * @param filePath * @param fileName ?? * @return String ?? */ public static String fileUp(MultipartFile file, String filePath, String fileName) { String extName = ""; try { if (file.getOriginalFilename().lastIndexOf(".") >= 0) { extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); } copyFile(file.getInputStream(), filePath, fileName + extName).replaceAll("-", ""); } catch (IOException e) { System.out.println(e); } return fileName + extName; }
From source file:common.utils.ImageUtils.java
/** * * @param in//from w w w . j av a2s . co m * @return image from given stream or null if no readers found * @throws java.io.IOException */ public static BufferedImageHolder readImage(MultipartFile in) throws IOException { InputStream is = in.getInputStream(); ImageInputStream iis = ImageIO.createImageInputStream(is); BufferedImageHolder bih = readImage(iis); is.close(); if (bih != null) bih.setMultipart(in); return bih; }
From source file:com.weavers.duqhan.util.GoogleBucketFileUploader.java
public static String uploadProductImage(MultipartFile file, Long productId) { InputStream targetStream = null; String imgUrl = "failure"; if (file != null) { try {//w w w . j a va2s . co m GoogleBucketFileUploader fileUploader = new GoogleBucketFileUploader(); Storage storage = fileUploader.authentication(); targetStream = file.getInputStream(); if (targetStream != null) { DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS"); DateTime dt = DateTime.now(DateTimeZone.UTC); String dtString = dt.toString(dtf); final String fileName = "img_" + productId.toString() + dtString + ".jpg"; // the inputstream is closed by default, so we don't need to close it here BlobInfo blobInfo = storage.create( BlobInfo.newBuilder(PRODUCT_BUCKET_NAME, fileName).setContentType("image/jpeg") // Modify access list to allow all users with link to read file .setAcl(new ArrayList<>( Arrays.asList(Acl.of(Acl.User.ofAllUsers(), Acl.Role.OWNER)))) .build(), targetStream); // return the public view link // System.out.println("https://storage.googleapis.com/duqhan-users/" + blobInfo.getName()); imgUrl = "https://storage.googleapis.com/duqhan-images/" + blobInfo.getName(); } } catch (IOException ex) { Logger.getLogger(GoogleBucketFileUploader.class.getName()).log(Level.SEVERE, null, ex); } } return imgUrl; }
From source file:com.glaf.core.util.UploadUtils.java
/** * ??/* ww w . j ava 2 s. c o m*/ * * @param request * @param fileParam * @return */ public static InputStream getInputStream(HttpServletRequest request, String fileParam) { MultipartFile mFile = getMultipartFile(request, fileParam); InputStream inputStream = null; try { if (mFile != null && !mFile.isEmpty()) { inputStream = mFile.getInputStream(); } } catch (Exception ex) { logger.error(ex.getMessage()); ex.printStackTrace(); } return inputStream; }
From source file:org.opentides.util.FileUtil.java
/** * Saves multipart file into disk/*from www .ja va2 s . c o m*/ * * @param multipartFile * @param dest * @return * @throws IOException */ public static boolean copyMultipartFile(final MultipartFile multipartFile, File dest) throws IOException { InputStream inStream = multipartFile.getInputStream(); OutputStream outStream = new FileOutputStream(dest); try { int len = 0; byte[] buffer = new byte[1024]; while ((len = inStream.read(buffer)) > 0) { outStream.write(buffer, 0, len); } outStream.flush(); return true; } catch (IOException ioe) { throw ioe; } finally { if (outStream != null) { outStream.close(); } if (inStream != null) { inStream.close(); } } }
From source file:org.openmrs.module.spreadsheetimport.SpreadsheetImportUtil.java
public static File importTemplate(SpreadsheetImportTemplate template, MultipartFile file, String sheetName, List<String> messages, boolean rollbackTransaction) throws Exception { if (file.isEmpty()) { messages.add("file must not be empty"); return null; }//from ww w. j a v a 2s .c o m // Open file Workbook wb = WorkbookFactory.create(file.getInputStream()); Sheet sheet; if (!StringUtils.hasText(sheetName)) { sheet = wb.getSheetAt(0); } else { sheet = wb.getSheet(sheetName); } // Header row Row firstRow = sheet.getRow(0); if (firstRow == null) { messages.add("Spreadsheet header row must not be null"); return null; } List<String> columnNames = new Vector<String>(); for (Cell cell : firstRow) { columnNames.add(cell.getStringCellValue()); } if (log.isDebugEnabled()) { log.debug("Column names: " + columnNames.toString()); } // Required column names List<String> columnNamesOnlyInTemplate = new Vector<String>(); columnNamesOnlyInTemplate.addAll(template.getColumnNamesAsList()); columnNamesOnlyInTemplate.removeAll(columnNames); if (columnNamesOnlyInTemplate.isEmpty() == false) { messages.add("required column names not present: " + toString(columnNamesOnlyInTemplate)); return null; } // Extra column names? List<String> columnNamesOnlyInSheet = new Vector<String>(); columnNamesOnlyInSheet.addAll(columnNames); columnNamesOnlyInSheet.removeAll(template.getColumnNamesAsList()); if (columnNamesOnlyInSheet.isEmpty() == false) { messages.add( "Extra column names present, these will not be processed: " + toString(columnNamesOnlyInSheet)); } // Process rows boolean skipThisRow = true; for (Row row : sheet) { if (skipThisRow == true) { skipThisRow = false; } else { boolean rowHasData = false; Map<UniqueImport, Set<SpreadsheetImportTemplateColumn>> rowData = template .getMapOfUniqueImportToColumnSetSortedByImportIdx(); for (UniqueImport uniqueImport : rowData.keySet()) { Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport); for (SpreadsheetImportTemplateColumn column : columnSet) { int idx = columnNames.indexOf(column.getName()); Cell cell = row.getCell(idx); Object value = null; // check for empty cell (new Encounter) if (cell == null) { rowHasData = true; column.setValue(""); continue; } switch (cell.getCellType()) { case Cell.CELL_TYPE_BOOLEAN: value = new Boolean(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_ERROR: value = new Byte(cell.getErrorCellValue()); break; case Cell.CELL_TYPE_FORMULA: case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { java.util.Date date = cell.getDateCellValue(); value = "'" + new java.sql.Timestamp(date.getTime()).toString() + "'"; } else { value = cell.getNumericCellValue(); } break; case Cell.CELL_TYPE_STRING: // Escape for SQL value = "'" + cell.getRichStringCellValue() + "'"; break; } if (value != null) { rowHasData = true; column.setValue(value); } else column.setValue(""); } } for (UniqueImport uniqueImport : rowData.keySet()) { Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport); boolean isFirst = true; for (SpreadsheetImportTemplateColumn column : columnSet) { if (isFirst) { // Should be same for all columns in unique import // System.out.println("SpreadsheetImportUtil.importTemplate: column.getColumnPrespecifiedValues(): " + column.getColumnPrespecifiedValues().size()); if (column.getColumnPrespecifiedValues().size() > 0) { Set<SpreadsheetImportTemplateColumnPrespecifiedValue> columnPrespecifiedValueSet = column .getColumnPrespecifiedValues(); for (SpreadsheetImportTemplateColumnPrespecifiedValue columnPrespecifiedValue : columnPrespecifiedValueSet) { // System.out.println(columnPrespecifiedValue.getPrespecifiedValue().getValue()); } } } } } if (rowHasData) { Exception exception = null; try { DatabaseBackend.validateData(rowData); String encounterId = DatabaseBackend.importData(rowData, rollbackTransaction); if (encounterId != null) { for (UniqueImport uniqueImport : rowData.keySet()) { Set<SpreadsheetImportTemplateColumn> columnSet = rowData.get(uniqueImport); for (SpreadsheetImportTemplateColumn column : columnSet) { if ("encounter".equals(column.getTableName())) { int idx = columnNames.indexOf(column.getName()); Cell cell = row.getCell(idx); if (cell == null) cell = row.createCell(idx); cell.setCellValue(encounterId); } } } } } catch (SpreadsheetImportTemplateValidationException e) { messages.add("Validation failed: " + e.getMessage()); return null; } catch (SpreadsheetImportDuplicateValueException e) { messages.add("found duplicate value for column " + e.getColumn().getName() + " with value " + e.getColumn().getValue()); return null; } catch (SpreadsheetImportSQLSyntaxException e) { messages.add("SQL syntax error: \"" + e.getSqlErrorMessage() + "\".<br/>Attempted SQL Statement: \"" + e.getSqlStatement() + "\""); return null; } catch (Exception e) { exception = e; } if (exception != null) { throw exception; } } } } // write back Excel file to a temp location File returnFile = File.createTempFile("sim", ".xls"); FileOutputStream fos = new FileOutputStream(returnFile); wb.write(fos); fos.close(); return returnFile; }
From source file:io.lavagna.web.api.UsersAdministrationControllerTest.java
@Test public void createUsers() throws JsonParseException, IOException { MultipartFile mpf = mock(MultipartFile.class); when(mpf.getInputStream()).thenReturn(new ByteArrayInputStream( "[{\"provider\" : \"demo\", \"username\" : \"username\"}]".getBytes("UTF-8"))); usersAdministrationController.createUsers(mpf); verify(userService).createUsers(Mockito.<List<UserToCreate>>any()); }