Example usage for org.springframework.web.multipart MultipartFile isEmpty

List of usage examples for org.springframework.web.multipart MultipartFile isEmpty

Introduction

In this page you can find the example usage for org.springframework.web.multipart MultipartFile isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Return whether the uploaded file is empty, that is, either no file has been chosen in the multipart form or the chosen file has no content.

Usage

From source file:hr.softwarecity.osijek.utility.Multimedia.java

/**
 * Method for uploading files/*from w ww. ja  va 2s  . c  om*/
 * @param path path to put file
 * @param file file to upload
 * @return path to file or Failed keyword on fail
 * @throws java.nio.file.FileSystemException
 * @throws java.io.FileNotFoundException
 */
public static String handleFileUpload(String path, MultipartFile file) throws IOException {
    Logger.getLogger("Multimedia.java").log(Logger.Level.INFO, "Initiating file upload");
    if (!file.isEmpty()) {
        byte[] bytes = file.getBytes();
        BufferedOutputStream stream = new BufferedOutputStream(
                new FileOutputStream(new File(path, file.getOriginalFilename())));
        stream.write(bytes);
        stream.close();
        Logger.getLogger("Multimedia.java").log(Logger.Level.INFO, "File uploaded");
        return path;
    } else {
        Logger.getLogger("Multimedia.java").log(Logger.Level.ERROR, "File size 0! ");
        return null;
    }
}

From source file:maku.mvc.services.ImageService.java

public static void updateAvatar(MultipartFile file, User user, String path) throws ImageOperationException {
    ImageService imageService = new ImageService();
    if (file.isEmpty()) {
        throw new ImageOperationException(Constants.FILE_NOT_CHOSEN);
    }//from w  w w  .  j  a va2  s .  c om
    if (!isJpeg(file)) {
        throw new ImageOperationException(Constants.UPDATE_AVATAR_ERROR);
    }
    if (!user.getImageName().equals(User.DEFAULT_IMAGE_NAME)) {
        if (delete(user.getImageName(), path)) {
            if (!save(user.getImageName(), path, file)) {
                throw new ImageOperationException(Constants.UPDATE_AVATAR_ERROR);
            }
        } else {
            throw new ImageOperationException(Constants.UPDATE_AVATAR_ERROR);
        }
    }
    if (!save(user.getImageName(), path, file)) {
        throw new ImageOperationException(Constants.UPDATE_AVATAR_ERROR);
    }
    user.setImageName("user" + user.getId() + ".jpg");
    imageService.userService.merge(user);
}

From source file:com.glaf.core.util.UploadUtils.java

/**
 * ????/* ww  w.  j  a v a2 s  .c  om*/
 * 
 * @param request
 * @param fileParam
 * @param fileType
 *            ?:jpg,gif,png,jpeg,swf
 * @param fileSize
 *            MB??
 * @return status=0 ?<br/>
 *         status=1 <br/>
 *         status=2 ?<br/>
 */
public static int getUploadStatus(HttpServletRequest request, String fileParam, String fileType,
        long fileSize) {
    int status = 0;
    MultipartFile mFile = getMultipartFile(request, fileParam);
    if (!mFile.isEmpty()) {
        String ext = FileUtils.getFileExt(mFile.getOriginalFilename());
        if (!StringUtils.containsIgnoreCase(fileType, ext)) {
            status = 1;
        }
        long size = mFile.getSize();
        if (fileSize != -1 && size > FileUtils.MB_SIZE * fileSize) {
            status = 2;
        }
    }
    return status;
}

From source file:com.glaf.core.util.UploadUtils.java

/**
 * ??/* www  .  j a va2  s .co  m*/
 * 
 * @param request
 * @param fileParam
 * @return
 */
public static byte[] getBytes(HttpServletRequest request, String fileParam) {
    MultipartFile mFile = getMultipartFile(request, fileParam);
    byte[] bytes = null;
    try {
        if (mFile != null && !mFile.isEmpty()) {
            bytes = mFile.getBytes();
        }
    } catch (Exception ex) {
        logger.error(ex.getMessage());
        ex.printStackTrace();
    }
    return bytes;
}

From source file:com.glaf.core.util.UploadUtils.java

/**
 * ??/*from  w ww.ja  v a2 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:com.glaf.core.util.UploadUtils.java

/**
 * // www . ja va 2  s.  c  om
 * 
 * @param request
 * @param fileParam
 * @param uploadDir
 *            ?
 * @return 
 */
public static String upload(HttpServletRequest request, String fileParam, String uploadDir) {
    MultipartFile mFile = getMultipartFile(request, fileParam);
    String filePath = "";
    try {
        String pathDir = mkdirs(getUploadAbsolutePath(uploadDir));
        if (!mFile.isEmpty()) {
            String fileName = mFile.getOriginalFilename();
            String saveName = rename(fileName);
            mFile.transferTo(new File(getUploadAbsolutePath(uploadDir) + pathDir + saveName));
            filePath = getUploadRelativePath(uploadDir) + pathDir + saveName;
        }
    } catch (Exception ex) {
        logger.error(ex.getMessage());
        ex.printStackTrace();
    }
    return filePath;
}

From source file:com.glaf.core.util.UploadUtils.java

/**
 * /*w w w . ja  va2  s . c o  m*/
 * 
 * @param request
 * @param fileParam
 * @param uploadDir
 *            ?
 * @return 
 */
public static String upload(HttpServletRequest request, String fileParam, String uploadDir,
        String fileNameParam) {
    MultipartFile mFile = getMultipartFile(request, fileParam);
    String filePath = "";
    if (StringUtils.isEmpty(uploadDir)) {
        uploadDir = UPLOAD_DIR;
    }
    try {
        FileUtils.mkdirs(getUploadAbsolutePath(uploadDir));
        if (!mFile.isEmpty()) {
            String fileName = mFile.getOriginalFilename();
            String saveName = "";
            if (StringUtils.isEmpty(fileNameParam)) {
                saveName = fileNameParam + getSuffix(fileName);
            } else {
                saveName = rename(fileName);
            }
            mFile.transferTo(new File(getUploadAbsolutePath(uploadDir) + saveName));
            filePath = uploadDir + saveName;
        }
    } catch (Exception ex) {
        logger.error(ex.getMessage());
        ex.printStackTrace();
    }
    return filePath;
}

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   w  w w.j  a v a 2  s .co 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:no.freecode.translator.web.AdminController.java

/**
 * Upload messages./*from   w w w  .  j  a v a 2  s  .  c o m*/
 * 
 * @throws IOException 
 */
@RequestMapping(method = RequestMethod.POST, value = "upload")
public @ResponseBody String upload(@RequestParam("file") MultipartFile file) throws IOException {

    if (!file.isEmpty()) {
        String filename = FilenameUtils.getName(file.getOriginalFilename());
        messageImporter.importData(file.getInputStream(), filename);
        return "Imported data from " + filename + "\n";

    } else {
        return "redirect:uploadFailure";
    }
}

From source file:com.yqboots.fss.web.form.FileUploadFormValidator.java

/**
 * {@inheritDoc}// ww w  .j a  v  a  2s.  co m
 */
@Override
public void validate(final Object target, final Errors errors) {
    final FileUploadForm form = (FileUploadForm) target;
    final MultipartFile file = form.getFile();
    if (file.isEmpty()) {
        errors.rejectValue(WebKeys.FILE, "I0002");
        return;
    }

    if (StringUtils.isBlank(form.getPath())) {
        errors.rejectValue(WebKeys.PATH, "I0004");
    }
}