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:gr.abiss.calipso.fs.FilePersistenceService.java

public default String saveFile(Field fileField, MultipartFile multipartFile, String filename) {
    FileDTO file;/*from w w w  . j a  v a2s.  c om*/
    try {
        file = new FileDTO.Builder().contentLength(multipartFile.getSize())
                .contentType(multipartFile.getContentType()).in(multipartFile.getInputStream()).path(filename)
                .build();

    } catch (IOException e) {
        throw new RuntimeException("Failed persisting file", e);
    }
    return this.saveFile(fileField, file);
}

From source file:org.jtalks.common.web.validation.ImageSizeValidator.java

/**
 * Check that file's size no more imageSize.
 *
 * @param multipartFile image that user want upload as avatar
 * @param context       validation context
 * @return {@code true} if validation successfull or false if fails
 *//*from ww  w.ja  v a2  s.  c  o  m*/
@Override
public boolean isValid(MultipartFile multipartFile, ConstraintValidatorContext context) {
    if (multipartFile.isEmpty()) {
        //assume that empty multipart file is valid to avoid validation message when user doesn't load nothing
        return true;
    }
    return multipartFile.getSize() / BYTES_IN_KILOBYTE < imageSize;
}

From source file:org.openmrs.module.sdmxhdintegration.web.controller.MessageUploadFormController.java

/**
 * Handles form submission// w w w .j a v a 2 s . c  o m
 * @param request the request
 * @param message the message
 * @param result the binding result
 * @param status the session status
 * @return the view
 * @throws IllegalStateException
 */
@RequestMapping(method = RequestMethod.POST)
public String handleSubmission(HttpServletRequest request, @ModelAttribute("message") SDMXHDMessage message,
        BindingResult result, SessionStatus status) throws IllegalStateException {

    DefaultMultipartHttpServletRequest req = (DefaultMultipartHttpServletRequest) request;
    MultipartFile file = req.getFile("sdmxhdMessage");
    File destFile = null;

    if (!(file.getSize() <= 0)) {
        AdministrationService as = Context.getAdministrationService();
        String dir = as.getGlobalProperty("sdmxhdintegration.messageUploadDir");
        String filename = file.getOriginalFilename();
        filename = "_" + (new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss")).format(new Date()) + "_" + filename;
        destFile = new File(dir + File.separator + filename);
        destFile.mkdirs();

        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            HttpSession session = request.getSession();
            session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                    "Could not save file. Make sure you have setup the upload directory using the configuration page and that the directory is readable by the tomcat user.");
            return "/module/sdmxhdintegration/messageUpload";
        }

        message.setZipFilename(filename);
    }

    new SDMXHDMessageValidator().validate(message, result);

    if (result.hasErrors()) {
        log.error("SDMXHDMessage object failed validation");
        if (destFile != null) {
            destFile.delete();
        }
        return "/module/sdmxhdintegration/messageUpload";
    }

    SDMXHDService service = Context.getService(SDMXHDService.class);
    ReportDefinitionService rds = Context.getService(ReportDefinitionService.class);
    service.saveMessage(message);

    // delete all existing mappings and reports
    List<KeyFamilyMapping> allKeyFamilyMappingsForMsg = service.getKeyFamilyMappingsFromMessage(message);
    for (Iterator<KeyFamilyMapping> iterator = allKeyFamilyMappingsForMsg.iterator(); iterator.hasNext();) {
        KeyFamilyMapping kfm = iterator.next();
        Integer reportDefinitionId = kfm.getReportDefinitionId();
        service.deleteKeyFamilyMapping(kfm);
        if (reportDefinitionId != null) {
            rds.purgeDefinition(rds.getDefinition(reportDefinitionId));
        }
    }

    // create initial keyFamilyMappings
    try {
        DSD dsd = Utils.getDataSetDefinition(message);
        List<KeyFamily> keyFamilies = dsd.getKeyFamilies();
        for (Iterator<KeyFamily> iterator = keyFamilies.iterator(); iterator.hasNext();) {
            KeyFamily keyFamily = iterator.next();

            KeyFamilyMapping kfm = new KeyFamilyMapping();
            kfm.setKeyFamilyId(keyFamily.getId());
            kfm.setMessage(message);
            service.saveKeyFamilyMapping(kfm);
        }
    } catch (Exception e) {
        log.error("Error parsing SDMX-HD Message: " + e, e);
        if (destFile != null) {
            destFile.delete();
        }

        service.deleteMessage(message);
        result.rejectValue("sdmxhdZipFileName", "upload.file.rejected",
                "This file is not a valid zip file or it does not contain a valid SDMX-HD DataSetDefinition");
        return "/module/sdmxhdintegration/messageUpload";
    }

    return "redirect:messages.list";
}

From source file:com.bvvy.photo.web.controller.PgerContoller.java

private String saveImage(MultipartFile mf) {
    Image image = new Image();
    image.setOldName(mf.getOriginalFilename());
    image.setSuffix(FilenameUtils.getExtension(mf.getOriginalFilename()));
    image.setSize(mf.getSize());
    image.setType(mf.getContentType());//from  w  w  w.j  a v a  2s  .c  o  m
    String path = FileUploadUtil.getInstance().saveOriginFile(mf);
    image.setNewName(path);
    imageService.add(image);
    return path;
}

From source file:com.fengduo.bee.web.controller.upload.FileUploadController.java

@RequestMapping(value = "/Upload", headers = "accept=*/*", produces = "application/json", method = RequestMethod.POST)
@ResponseBody// w ww.jav a  2s.  c o  m
public DeferredResult<String> Upload(MultipartFile upload) {
    DeferredResult<String> deferredResult = new DeferredResult<String>();

    long size = upload.getSize();
    if (size == 0) {
        deferredResult.setResult("-1");
        return deferredResult;
    }
    PicsInfoEnum picInfoEnum = PicsInfoEnum.AVATAR_IMG;
    if (picInfoEnum == null) {
        deferredResult.setResult("-1");
        return deferredResult;
    }
    int maxSize = picInfoEnum.getMaxSize();
    if (size > maxSize) {
        deferredResult.setResult("-1");
        return deferredResult;
    }
    // ???
    String suffix = getSuffix(upload.getOriginalFilename());
    boolean isLegal = checkSuffixLegal(picInfoEnum.getSuffixs(), suffix);
    if (!isLegal) {
        deferredResult.setResult("-1");
        return deferredResult;
    }
    long userId = getCurrentUserId();
    String relativeUrl = null;
    relativeUrl = picInfoEnum.getDirPrefix() + "/" + userId + "/";
    final String _filePath = relativeUrl;
    Result result = fileService.createFilePath(upload, new IFileCreate() {

        public String build(String filePath, String suffix) {
            return _filePath + filePath + suffix;
        }
    });
    if (result.isSuccess()) {
        deferredResult.setResult("http://fengduo.co" + result.getData().toString());
        return deferredResult;
    } else {
        deferredResult.setResult("IOError");
        return deferredResult;
    }
}

From source file:se.vgregion.social.controller.publicprofile.PublicProfileController.java

@ActionMapping(params = "action=uploadProfileImage")
public void uploadProfileImage(MultipartActionRequest request) throws IOException, SocialServiceException {
    MultipartFile profileImageInput = request.getFile("profileImage");

    if (profileImageInput == null || profileImageInput.getSize() <= 0) {
        return;/*from   w  ww.  j av  a  2  s . c o  m*/
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    final int croppedWidth = 160;
    final int croppedHeight = 160;

    BufferedImage bufferedImage = ImageIO.read(profileImageInput.getInputStream());

    ImageUtil.writeImageToStream(baos, croppedWidth, croppedHeight, bufferedImage);

    long loggedInUserId = getLoggedInUserId(request);
    service.updatePortrait(loggedInUserId, baos.toByteArray());
}

From source file:de.iteratec.iteraplan.presentation.dialog.ExcelImport.ImportFrontendServiceImpl.java

/**
 * @param memBean//  w ww  .j  av  a2s. co  m
 * @return true if successful, false if not.
 */
private boolean handleUploadedFile(MassdataMemBean memBean) {
    memBean.resetResultMessages();
    MultipartFile file = memBean.getFileToUpload();
    if (file == null || file.getSize() == 0) {
        memBean.addErrorMessage(MessageAccess.getString("import.no.file"));
        return false;
    }
    if (memBean.getImportStrategy() == null) {
        memBean.addErrorMessage(MessageAccess.getString("import.no.strategy"));
        return false;
    }
    //TODO use the import strategy

    String originalFilename = file.getOriginalFilename();
    memBean.setFileName(originalFilename);

    if (determineImportType(memBean, originalFilename)) {
        if (file.getSize() > MAX_FILESIZE_BYTE) {
            memBean.addErrorMessage(MessageFormat.format(MessageAccess.getString("import.too.large"),
                    Long.valueOf(MAX_FILESIZE_BYTE)));
            return false;
        }

        setFileContentToMemBean(memBean, file);
        return true;
    }

    return false;
}

From source file:de.iteratec.iteraplan.presentation.dialog.ExcelImport.ImportFrontendServiceImpl.java

private boolean handleTimeseriesFile(MassdataMemBean memBean, MultipartFile file) {
    memBean.resetResultMessages();/*from w  ww.ja va 2  s. c o m*/
    if (file == null || file.getSize() == 0) {
        memBean.addErrorMessage(MessageAccess.getString("import.no.file"));
        return false;
    }

    String originalFilename = file.getOriginalFilename();
    memBean.setFileName(originalFilename);

    if (!hasAcceptableExcelFileExtension(originalFilename)) {
        memBean.setImportType(null);
        memBean.setFileContent(null);
        memBean.addErrorMessage(MessageAccess.getString("import.wrong.type"));
        return false;
    }

    memBean.setImportType(ImportType.EXCEL);
    setFileContentToMemBean(memBean, file);
    return true;
}

From source file:se.gothiaforum.controller.actorsform.AddImageController.java

/**
 * Adds the logo to the image gallery for the actors organization.
 * /*  w  w  w. j a v a  2s  .  c om*/
 * @param request
 *            the request
 * @param response
 *            the response
 * @throws Exception
 *             the exception
 */
@RequestMapping(params = "action=addActorImage")
public void addActorImage(ActionRequest request, ActionResponse response, Model model) throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
    ActorArticle actorArticle = actorsService.getActorsArticle(themeDisplay);
    long actorGroupId = actorArticle.getGroupId();
    long userId = themeDisplay.getUserId();

    List<String> errors = new ArrayList<String>();

    if (request instanceof MultipartActionRequest) {
        MultipartActionRequest multipartRequest = (MultipartActionRequest) request;
        MultipartFile multipartFile = multipartRequest.getFile("file");

        if (multipartFile.getSize() == 0) {

            ServiceContext serviceContext = ServiceContextFactory.getInstance(JournalArticle.class.getName(),
                    request);

            String imageURL = actorsService
                    .getImageURL((ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY));

            actorArticle.setImageUuid(imageURL);

            JournalArticle article = actorsService.updateActors(actorArticle, userId, serviceContext,
                    actorArticle.getTagsStr(), themeDisplay.getScopeGroupId());

            Indexer indexer = IndexerRegistryUtil.getIndexer(JournalArticle.class.getName());
            indexer.reindex(article);

        } else {

            String originalFileName = multipartFile.getOriginalFilename();
            String mimeType = multipartFile.getContentType();

            validator.validate(multipartFile, errors);

            if (!errors.isEmpty()) {
                model.addAttribute("errorList", errors);
                response.setRenderParameter("view", "showImageActorsForm");
            } else {

                byte[] logoInByte = multipartFile.getBytes();

                DLFileEntry image = actorsService.addImage(userId, actorGroupId, originalFileName, logoInByte,
                        mimeType, themeDisplay.getPortletDisplay().getRootPortletId());

                ServiceContext serviceContext = ServiceContextFactory
                        .getInstance(JournalArticle.class.getName(), request);

                // Assume there is no parent folder. Otherwise we would need to concatenate a like "{parentFolderId}/{image.getFolderId}
                String imageUrl = ActorsServiceUtil.getImageUrl(image);

                actorArticle.setImageUuid(imageUrl);

                JournalArticle article = actorsService.updateActors(actorArticle, userId, serviceContext,
                        actorArticle.getTagsStr(), themeDisplay.getScopeGroupId());

                Indexer indexer = IndexerRegistryUtil.getIndexer(JournalArticle.class.getName());
                indexer.reindex(article);

            }
        }
    }
}

From source file:fr.hoteia.qalingo.web.mvc.controller.catalog.AssetController.java

@RequestMapping(value = "/asset-form.html*", method = RequestMethod.POST)
public ModelAndView assetEdit(final HttpServletRequest request, final HttpServletResponse response,
        @Valid AssetForm assetForm, BindingResult result, ModelMap modelMap) throws Exception {

    if (result.hasErrors()) {
        return display(request, response, modelMap);
    }//from  w w  w .j a  va  2s . c o m

    final String currentAssetId = assetForm.getId();
    final Asset asset = productMarketingService.getProductMarketingAssetById(currentAssetId);
    final String currentAssetCode = asset.getCode();

    MultipartFile multipartFile = assetForm.getFile();
    if (multipartFile != null) {
        long size = multipartFile.getSize();
        asset.setFileSize(size);
    }

    try {
        if (multipartFile.getSize() > 0) {
            String pathProductMarketingImage = multipartFile.getOriginalFilename();
            String assetFileRootPath = engineSettingService.getAssetFileRootPath().getDefaultValue();
            assetFileRootPath.replaceAll("\\\\", "/");
            if (assetFileRootPath.endsWith("/")) {
                assetFileRootPath = assetFileRootPath.substring(0, assetFileRootPath.length() - 1);
            }
            String assetProductMarketingFilePath = engineSettingService.getAssetProductMarketingFilePath()
                    .getDefaultValue();
            assetProductMarketingFilePath.replaceAll("\\\\", "/");
            if (assetProductMarketingFilePath.endsWith("/")) {
                assetProductMarketingFilePath = assetProductMarketingFilePath.substring(0,
                        assetProductMarketingFilePath.length() - 1);
            }
            if (!assetProductMarketingFilePath.startsWith("/")) {
                assetProductMarketingFilePath = "/" + assetProductMarketingFilePath;
            }

            String absoluteFilePath = assetFileRootPath + assetProductMarketingFilePath + "/"
                    + asset.getType().getPropertyKey().toLowerCase() + "/" + pathProductMarketingImage;

            InputStream inputStream = multipartFile.getInputStream();
            URI url = new URI(absoluteFilePath);
            File fileAsset;
            try {
                fileAsset = new File(url);
            } catch (IllegalArgumentException e) {
                fileAsset = new File(url.getPath());
            }
            OutputStream outputStream = new FileOutputStream(fileAsset);
            int readBytes = 0;
            byte[] buffer = new byte[8192];
            while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) {
                outputStream.write(buffer, 0, readBytes);
            }
            outputStream.close();
            inputStream.close();
            asset.setPath(pathProductMarketingImage);
        }

        // UPDATE ASSET
        webBackofficeService.updateProductMarketingAsset(asset, assetForm);

    } catch (Exception e) {
        LOG.error("Can't save/update asset file!", e);
    }

    final String urlRedirect = backofficeUrlService.buildAssetDetailsUrl(currentAssetCode);
    return new ModelAndView(new RedirectView(urlRedirect));
}