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

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

Introduction

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

Prototype

long getSize();

Source Link

Document

Return the size of the file in bytes.

Usage

From source file:ubic.gemma.web.util.upload.CommonsMultipartMonitoredResolver.java

@Override
public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
    String enc = determineEncoding(request);

    ServletFileUpload fileUpload = this.newFileUpload(request);
    DiskFileItemFactory newFactory = (DiskFileItemFactory) fileUpload.getFileItemFactory();
    fileUpload.setSizeMax(sizeMax);/*ww  w  .  j a v  a2s  .com*/
    newFactory.setRepository(this.uploadTempDir);
    fileUpload.setHeaderEncoding(enc);

    try {
        MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<>();
        Map<String, String[]> multipartParams = new HashMap<>();

        // Extract multipart files and multipart parameters.
        List<?> fileItems = fileUpload.parseRequest(request);
        for (Object fileItem1 : fileItems) {
            FileItem fileItem = (FileItem) fileItem1;
            if (fileItem.isFormField()) {
                String value;
                String fieldName = fileItem.getFieldName();

                try {
                    value = fileItem.getString(enc);
                } catch (UnsupportedEncodingException ex) {
                    logger.warn("Could not decode multipart item '" + fieldName + "' with encoding '" + enc
                            + "': using platform default");
                    value = fileItem.getString();
                }

                String[] curParam = multipartParams.get(fieldName);
                if (curParam == null) {
                    // simple form field
                    multipartParams.put(fieldName, new String[] { value });
                } else {
                    // array of simple form fields
                    String[] newParam = StringUtils.addStringToArray(curParam, value);
                    multipartParams.put(fieldName, newParam);
                }
            } else {
                // multipart file field
                MultipartFile file = new CommonsMultipartFile(fileItem);
                multipartFiles.set(file.getName(), file);
                if (logger.isDebugEnabled()) {
                    logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize()
                            + " bytes with original filename [" + file.getOriginalFilename() + "]");
                }
            }
        }
        return new DefaultMultipartHttpServletRequest(request, multipartFiles, multipartParams, null);
    } catch (FileUploadException ex) {
        return new FailedMultipartHttpServletRequest(request, ex.getMessage());
    }
}

From source file:ubic.gemma.web.util.upload.FileUploadUtil.java

public static File copyUploadedFile(MultipartFile multipartFile, HttpServletRequest request)
        throws IOException {
    log.info("Copying the file:" + multipartFile);
    String copiedFilePath = getLocalUploadLocation(request, multipartFile);

    File copiedFile = new File(copiedFilePath);

    copyFile(multipartFile, copiedFile);

    if (!copiedFile.canRead() || copiedFile.length() == 0) {
        throw new IllegalArgumentException("Uploaded file is not readable or of size zero");
    }//www.  j  a va  2 s.  c o  m

    if (request != null) {
        String link = getContextUploadPath(); // FIXME - this will not yield a valid url.
        request.setAttribute("link", link + multipartFile.getOriginalFilename());

        // place the data into the request for retrieval on next page
        request.setAttribute("fileName", multipartFile.getOriginalFilename());
        request.setAttribute("contentType", multipartFile.getContentType());
        request.setAttribute("size", multipartFile.getSize() + " bytes");
        request.setAttribute("location", copiedFilePath);
    }
    return copiedFile;

}

From source file:ubic.gemma.web.util.upload.FileUploadUtil.java

private static void copyFile(MultipartFile file, File copiedFile) throws IOException {
    log.info("Copying file " + file + " (" + file.getSize() + " bytes)");
    // write the file to the file specified
    try (InputStream stream = file.getInputStream()) {
        copy(copiedFile, stream);// ww w.  ja  va  2s.co  m
        log.info("Done copying to " + copiedFile);
    }
}

From source file:war.controller.WorkboardController.java

@RequestMapping(value = "/addEngineeringData", method = RequestMethod.POST)
public String addEngineeringDataToWorkboard(
        @RequestParam(value = "file", required = true) MultipartFile uploadfile,
        @RequestParam(value = "sourceType", required = true) String sourceType,
        @RequestParam(value = "engVariable", required = true) String engVariableName,
        @RequestParam(value = "engVariableCategory", required = true) String engVariableCategory,
        @RequestParam(value = "id", required = true) Integer userStoryId,
        @RequestParam(value = "displayType", required = true) String displayTypeString,
        RedirectAttributes attributes) {
    logger.info("Inside addEngineeringDataToWorkBoard");

    UserStory userStory = null;/*  ww w . j ava2 s.co m*/
    try {
        userStory = userStoryDao.find(userStoryId);

        if (!(SecurityHelper.IsCurrentUserAllowedToAccess(userStory))) // Security: ownership check
            throw new AccessDeniedException(ERR_ACCESS_DENIED);

        EngineeringModelVariable engVariable = null;
        try {
            engVariable = engineeringModelVariableDao.find(engVariableName, engVariableCategory);
        } catch (NoResultException e) {
            logger.info(e.getMessage() + "(" + engVariableName + ")");
            throw (e);
        }

        DataElement.DisplayType displayType = DataElement.DisplayType.fromString(displayTypeString);

        if (sourceType.equals("upload")) {
            logger.info("Excel File Upload");

            int lastIndex = uploadfile.getOriginalFilename().lastIndexOf('.');
            //String fileName = uploadfile.getOriginalFilename().substring(0, lastIndex);
            String fileExtension = uploadfile.getOriginalFilename().substring(lastIndex + 1);
            String fileType = uploadfile.getContentType();

            // Checks the file extension & MIME type
            if (uploadfile.getSize() == 0) {
                throw new IllegalArgumentException(WorkboardController.ERR_UPLOAD_NO_FILE);
            } else if (!(fileType.equals("application/vnd.ms-excel")
                    || fileType.equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                    || !(fileExtension.equals("xls") || fileExtension.equals("xlsx"))) {
                throw new InvalidFormatException(WorkboardController.ERR_INVALID_FILE_FORMAT);
            }

            ByteArrayInputStream bis = new ByteArrayInputStream(uploadfile.getBytes());
            // HSSFWorkbook and HSSFSheet for XLS, XSSFWorkbook and XSSFSheet for XLSX
            HSSFWorkbook workbook = new HSSFWorkbook(bis);

            // Extract & save Engineering Model Asset
            EngineeringModelAsset asset = extractEngineeringOutputAsset(workbook);
            asset = engineeringModelAssetDao.save(asset);

            // Extract and save Engineering Model Data
            List<EngineeringModelData> extractedDataList = extractEngineeringOutputData(workbook, userStory,
                    engVariable, asset);

            // Create a data element using the extracted data if there is some
            if (extractedDataList != null && extractedDataList.size() > 0) {

                for (EngineeringModelData data : extractedDataList) {
                    engineeringModelDataDao.save(data);
                }

                DataElementEngineeringModel de = new DataElementEngineeringModel(new Date(),
                        "Concrete deterioration for " + asset.getAssetCode(), true, 0, displayType, userStory,
                        extractedDataList);
                dataElementDao.save(de);

                userStory = userStoryDao.find(userStoryId);
                attributes.addFlashAttribute("successMessage", WorkboardController.MSG_ENG_DATA_ADDED);
            } else {
                throw new NoResultException(WorkboardController.ERR_NO_DATA_ENG_MODEL);
            }
        } else if (sourceType.equals("example")) {
            logger.info("Example selected");

            //Find the Data
            List<EngineeringModelData> engineeringModelDataList = engineeringModelDataDao
                    .find(userStory.getSeaport().getRegion(), engVariable);

            // Create the data element
            if (engineeringModelDataList != null && engineeringModelDataList.size() > 0) {
                String dataElementTitle = "Concrete deterioration for "
                        + engineeringModelDataList.get(0).getAsset().getAssetCode();
                DataElementEngineeringModel de = new DataElementEngineeringModel(new Date(), dataElementTitle,
                        true, 0, displayType, userStory, engineeringModelDataList);
                dataElementDao.save(de);

                userStory = userStoryDao.find(userStoryId);
                attributes.addFlashAttribute("successMessage", WorkboardController.MSG_ENG_DATA_ADDED);
            } else {
                throw new NoResultException(WorkboardController.ERR_NO_DATA_ENG_MODEL_EXAMPLE);
            }
        }
    } catch (NoResultException e) {
        attributes.addFlashAttribute("warningMessage", e.getMessage());
    } catch (InvalidFormatException e) {
        attributes.addFlashAttribute("warningMessage", e.getMessage());
    } catch (IllegalArgumentException e) {
        attributes.addFlashAttribute("warningMessage", e.getMessage());
    } catch (IOException e) {
        attributes.addFlashAttribute("errorMessage", e.getMessage());
    }

    return "redirect:/auth/workboard?user=" + SecurityHelper.getCurrentlyLoggedInUsername()
            + "#tabs-applications";
}