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:org.bonitasoft.web.designer.controller.asset.AssetService.java

/**
 * Upload a local asset/*www.  java  2s . c o m*/
 */
public Asset upload(MultipartFile file, T component, String type) {
    AssetType assetType = AssetType.getAsset(type);

    checkArgument(file != null && !file.isEmpty(),
            "Part named [file] is needed to successfully import a component");
    checkArgument(assetType != null, ASSET_TYPE_IS_REQUIRED);

    try {

        if (AssetType.JSON.getPrefix().equals(type)) {
            checkWellFormedJson(file.getBytes());
        }

        final Asset asset = new Asset().setName(getOriginalFilename(file.getOriginalFilename()))
                .setType(assetType).setOrder(getNextOrder(component));

        Optional<Asset> existingAsset = Iterables.<Asset>tryFind(component.getAssets(), new Predicate<Asset>() {

            @Override
            public boolean apply(Asset element) {
                return asset.equalsWithoutComponentId(element);
            }
        });
        if (existingAsset.isPresent()) {
            asset.setId(existingAsset.get().getId());
        }

        return save(component, asset, file.getBytes());

    } catch (IOException e) {
        logger.error("Asset creation" + e);
        throw new ServerImportException(format("Error while uploading asset in %s [%s]",
                file.getOriginalFilename(), repository.getComponentName()), e);
    }
}

From source file:org.cloud.mblog.utils.FileUtil.java

/**
 * ?/*w  w w  . ja  v  a 2s . c o  m*/
 *
 * @param file
 * @return
 */
public static ImageData uploadSingleFile(MultipartFile file, HttpServletRequest request, Boolean haveThumb) {
    if (!file.isEmpty()) {
        LocalDateTime now = LocalDateTime.now();
        String imageRelativeFolder = getImageRelativePathByDate(now);
        String thumbRelativeFolder = getThumbRelativePathByDate(now);

        String sourceFileName = file.getOriginalFilename();
        String fileType = sourceFileName.substring(sourceFileName.lastIndexOf(".") + 1);
        String fileName = getWidFileName(fileType);
        File targetFile = new File(LOCALROOT + imageRelativeFolder + File.separator + fileName);
        try {
            file.transferTo(targetFile);
            logger.info("Upload file path: " + targetFile.getAbsolutePath());
            if (haveThumb) {
                File thumbFile = new File(LOCALROOT + thumbRelativeFolder + File.separator + fileName);
                ImageUtil.zoomImage(targetFile, thumbFile, 300);
            }
            return new ImageData(fileName, file.getSize(), imageRelativeFolder, thumbRelativeFolder);
        } catch (Exception e) {
            logger.error("error", e);
        }
    }
    return null;
}

From source file:org.cloud.mblog.utils.FileUtil.java

/**
 * //w ww  . j a  va2  s .  com
 * 
 * @param file ??
 * @param request http
 * @return
 */
public static String uploadCommonFile(MultipartFile file, HttpServletRequest request) {
    if (!file.isEmpty()) {
        String commonRelativeFolder = getTempRelativePath();
        String sourceFileName = file.getOriginalFilename();
        String fileType = sourceFileName.substring(sourceFileName.lastIndexOf(".") + 1);
        String fileName = getWidFileName(fileType);
        File targetFile = new File(LOCALROOT + commonRelativeFolder + File.separator + fileName);
        try {
            file.transferTo(targetFile);
            logger.info("Upload file path: " + targetFile.getAbsolutePath());
            return targetFile.getAbsolutePath();
        } catch (Exception e) {
            logger.error("error", e);
        }
    }
    return null;
}

From source file:org.egov.eis.web.controller.masters.employee.ViewAndUpdateEmployeController.java

@RequestMapping(value = "/update/{code}", method = RequestMethod.POST)
public String update(@Valid @ModelAttribute final Employee employee, final BindingResult errors,
        final RedirectAttributes redirectAttrs, final Model model, @RequestParam final MultipartFile file,
        @RequestParam final String removedJurisdictionIds, @RequestParam final String removedassignIds) {

    final Boolean codeExists = employeeService.validateEmployeeCode(employee);
    if (codeExists)
        errors.rejectValue("code", "Unique.employee.code");

    try {/*  w  ww .j av a 2 s.c  o m*/
        if (!file.isEmpty())
            employee.setSignature(file.getBytes());
    } catch (final IOException e) {
        LOGGER.error("Error in loading Employee Signature" + e.getMessage(), e);
    }
    jurisdictionService.removeDeletedJurisdictions(employee, removedJurisdictionIds);
    final String positionName = employeeService.validatePosition(employee, removedassignIds);
    if (StringUtils.isNotBlank(positionName)) {
        setDropDownValues(model);
        final String fieldError = messageSource.getMessage("position.exists.workflow",
                new String[] { positionName }, null);
        model.addAttribute("error", fieldError);
        return EMPLOYEEFORM;
    }
    if (!employeeService.primaryAssignmentExists(employee) && employee.isActive())
        errors.rejectValue("assignments", "primary.assignment");

    if (employeeService.primaryAssignExistsForSamePeriod(employee))
        errors.rejectValue("assignments", "primary.assignment.daterange");

    if (errors.hasErrors()) {
        setDropDownValues(model);
        model.addAttribute("mode", "update");
        return EMPLOYEEFORM;
    }

    String image = null;
    if (null != employee.getSignature())
        image = Base64.encodeBytes(employee.getSignature());
    model.addAttribute(IMAGE, image);

    employeeService.update(employee);
    redirectAttrs.addFlashAttribute("employee", employee);
    model.addAttribute("message", "Employee updated successfully");
    return EMPLOYEESUCCESS;
}

From source file:org.encuestame.mvc.page.FileUploadController.java

/**
 * Upload Profile for User Account./* w w w . ja  va 2 s  .  c  o m*/
 * @param multipartFile
 * @return
 */
@PreAuthorize("hasRole('ENCUESTAME_USER')")
@RequestMapping(value = "/file/upload/profile", method = RequestMethod.POST)
public ModelAndView handleUserProfileFileUpload(@RequestParam("file") MultipartFile multipartFile) {
    ModelAndView mav = new ModelAndView(new MappingJackson2JsonView());
    if (!multipartFile.isEmpty()) {
        log.debug(multipartFile.getName());
        String orgName = multipartFile.getOriginalFilename();
        log.debug("org name " + orgName);
        //TODO: convert name to numbers, MD5 hash.
        String filePath = null;
        try {
            log.debug("getting file path for this user");
            filePath = getPictureService()
                    .getAccountUserPicturePath(getSecurityService().getUserAccount(getUserPrincipalUsername()));
            InputStream stream = multipartFile.getInputStream();
            try {
                //generate thumbnails
                thumbnailGeneratorEngine.generateThumbnails(PathUtil.DEFAUL_PICTURE_PREFIX, stream,
                        multipartFile.getContentType(), filePath);
            } catch (Exception e) {
                //e.printStackTrace();
                log.error(e);
            } finally {
                stream.close();
            }
            //TODO: after save image, we need relationship user with profile picture.
            //I suggest store ID on user account table, to retrieve easily future profile image.
            //BUG 102
        } catch (IllegalStateException e) {
            //e.printStackTrace();
            log.error("File uploaded failed:" + orgName);
        } catch (IOException e) {
            //e.printStackTrace();
            log.error("File uploaded failed:" + orgName);
        } catch (EnMeNoResultsFoundException e) {
            ///e.printStackTrace();
            log.error("File uploaded failed:" + orgName);
        } catch (EnmeFailOperation e) {
            //e.printStackTrace();
            log.error("File uploaded failed:" + orgName);
        }
        // Save the file here
        mav.addObject("status", "saved");
        mav.addObject("id", filePath);
    } else {
        mav.addObject("status", "failed");
    }
    return mav;
}

From source file:org.esupportail.publisher.service.FileService.java

private Pair<Boolean, MultipartException> isAuthorizedMimeType(final MultipartFile file,
        final FileUploadHelper fileUploadHelper) {
    if (file != null && !file.isEmpty()) {
        final String detectedType = file.getContentType();
        log.debug("Detected file Content informations {} ", detectedType);

        if (detectedType != null && fileUploadHelper.getAuthorizedMimeType() != null
                && fileUploadHelper.getAuthorizedMimeType().contains(detectedType)) {
            return new Pair<Boolean, MultipartException>(true, null);
        }//from w w  w  . ja  v a 2s .  com
        log.warn("File {} with ContentType {} isn't authorized", file.getName(), detectedType);
        return new Pair<Boolean, MultipartException>(false, new UnsupportedMimeTypeException(detectedType));
    }
    return new Pair<Boolean, MultipartException>(false, new MultipartException(
            "Unable to read the content type of an empty file", new NullArgumentException("file")));
}

From source file:org.fao.geonet.api.pages.PagesAPI.java

/**
 * Check correct format.//w ww  .  j a  va2s. com
 *
 * @param data the data
 * @param link the link
 * @param format the format
 */
private void checkCorrectFormat(final MultipartFile data, final String link, final Page.PageFormat format) {
    // Cannot set format to LINK and upload a file
    if (Page.PageFormat.LINK.equals(format) && data != null && !data.isEmpty()) {
        throw new IllegalArgumentException("Wrong format.");
    }

    // Cannot set a link without setting format to LINK
    if (!Page.PageFormat.LINK.equals(format) && !StringUtils.isBlank(link)) {
        throw new IllegalArgumentException("Wrong format.");
    }
}

From source file:org.fao.geonet.api.pages.PagesAPI.java

/**
 * Check that link or a file is defined.
 *
 * @param data the data/*from   ww w.j  a va 2  s . c om*/
 * @param link the link
 */
private void checkMandatoryContent(final MultipartFile data, final String link) {
    // Cannot set both: link and file
    if (StringUtils.isBlank(link) && (data == null || data.isEmpty())) {
        throw new IllegalArgumentException("A content associated to the page, a link or a file, is mandatory.");
    }
}

From source file:org.fao.geonet.api.pages.PagesAPI.java

/**
 * Check unique content.// w w w. j av a 2 s. c o  m
 *
 * @param data the data
 * @param link the link
 */
private void checkUniqueContent(final MultipartFile data, final String link) {
    // Cannot set both: link and file
    if (!StringUtils.isBlank(link) && data != null && !data.isEmpty()) {
        throw new IllegalArgumentException(
                "A content associated to the page, a link or a file, is mandatory. But is not possible to associate both to the same page.");
    }
}

From source file:org.fao.geonet.api.pages.PagesAPI.java

/**
 * Set the content with file or with provided link
 *
 * @param data the file/*  w  w w  .  j a va  2 s .  c  o  m*/
 * @param link the link
 * @param page the page to set content
 */
private void fillContent(final MultipartFile data, final String link, final Page page) {
    byte[] bytesData = null;
    if (data != null && !data.isEmpty()) {
        checkFileType(data);
        try {
            bytesData = data.getBytes();
        } catch (final Exception e) {
            // Wrap into managed exception
            throw new WebApplicationException(e);
        }
        page.setData(bytesData);
    }

    if (link != null && !UrlUtils.isValidRedirectUrl(link)) {
        throw new IllegalArgumentException("The link provided is not valid");
    } else {
        page.setLink(link);
    }
}