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.springframework.batch.admin.web.BatchFileController.java

@RequestMapping(value = "/{path}", method = RequestMethod.POST)
public String upload(@PathVariable String path, @RequestParam MultipartFile file, ModelMap model,
        @RequestParam(defaultValue = "0") int startFile, @RequestParam(defaultValue = "20") int pageSize,
        @ModelAttribute("date") Date date, Errors errors) throws Exception {

    String originalFilename = file.getOriginalFilename();
    if (file.isEmpty()) {
        errors.reject("file.upload.empty", new Object[] { originalFilename },
                "File upload was empty for filename=[" + HtmlUtils.htmlEscape(originalFilename) + "]");
        return null;
    }/*from w ww  . ja v a  2 s.  co m*/

    try {
        FileInfo dest = fileService.createFile(path + "/" + originalFilename);
        file.transferTo(fileService.getResource(dest.getPath()).getFile());
        fileService.publish(dest);
        model.put("uploaded", dest.getPath());
    } catch (IOException e) {
        errors.reject("file.upload.failed", new Object[] { originalFilename },
                "File upload failed for " + HtmlUtils.htmlEscape(originalFilename));
    } catch (Exception e) {
        String message = "File upload failed downstream processing for "
                + HtmlUtils.htmlEscape(originalFilename);
        if (logger.isDebugEnabled()) {
            logger.debug(message, e);
        } else {
            logger.info(message);
        }
        errors.reject("file.upload.failed.downstream", new Object[] { originalFilename }, message);
    }

    return null;
}

From source file:org.springframework.batch.admin.web.FileController.java

@RequestMapping(value = "/files/{path}", method = RequestMethod.POST)
public String upload(@PathVariable String path, @RequestParam MultipartFile file, ModelMap model,
        @RequestParam(defaultValue = "0") int startFile, @RequestParam(defaultValue = "20") int pageSize,
        @ModelAttribute("date") Date date, Errors errors) throws Exception {

    String originalFilename = file.getOriginalFilename();
    if (file.isEmpty()) {
        errors.reject("file.upload.empty", new Object[] { originalFilename },
                "File upload was empty for filename=[" + HtmlUtils.htmlEscape(originalFilename) + "]");
        list(model, startFile, pageSize);
        return "files";
    }// w  ww. java  2s  .  com

    try {
        FileInfo dest = fileService.createFile(path + "/" + originalFilename);
        file.transferTo(fileService.getResource(dest.getPath()).getFile());
        fileService.publish(dest);
        model.put("uploaded", dest.getPath());
    } catch (IOException e) {
        errors.reject("file.upload.failed", new Object[] { originalFilename },
                "File upload failed for " + HtmlUtils.htmlEscape(originalFilename));
    } catch (Exception e) {
        String message = "File upload failed downstream processing for "
                + HtmlUtils.htmlEscape(originalFilename);
        if (logger.isDebugEnabled()) {
            logger.debug(message, e);
        } else {
            logger.info(message);
        }
        errors.reject("file.upload.failed.downstream", new Object[] { originalFilename }, message);
    }

    if (errors.hasErrors()) {
        list(model, startFile, pageSize);
        return "files";
    }

    return "redirect:files";

}

From source file:org.springframework.data.hadoop.admin.web.TemplateController.java

@RequestMapping(value = "/templates/{path}", method = RequestMethod.POST)
public String upload(@PathVariable String path, @RequestParam MultipartFile file, ModelMap model,
        @RequestParam(defaultValue = "0") int startFile, @RequestParam(defaultValue = "20") int pageSize,
        @ModelAttribute("date") Date date, Errors errors) throws Exception {

    String originalFilename = file.getOriginalFilename();
    if (file.isEmpty()) {
        errors.reject("file.upload.empty", new Object[] { originalFilename },
                "File upload was empty for filename=[" + HtmlUtils.htmlEscape(originalFilename) + "]");
        list(model, startFile, pageSize);
        return "workflows";
    }//ww  w .j a va  2s.c  o m

    try {
        FileInfo dest = templateService.createFile(path + "/" + originalFilename);
        file.transferTo(templateService.getResource(dest.getPath()).getFile());
        templateService.publish(dest);
        model.put("uploaded", dest.getPath());
    } catch (IOException e) {
        errors.reject("file.upload.failed", new Object[] { originalFilename },
                "File upload failed for " + HtmlUtils.htmlEscape(originalFilename));
    } catch (Exception e) {
        String message = "File upload failed downstream processing for "
                + HtmlUtils.htmlEscape(originalFilename);
        if (logger.isDebugEnabled()) {
            logger.debug(message, e);
        } else {
            logger.info(message);
        }
        errors.reject("file.upload.failed.downstream", new Object[] { originalFilename }, message);
    }

    if (errors.hasErrors()) {
        list(model, startFile, pageSize);
        return "templates";
    }

    return "redirect:templates";

}

From source file:org.springframework.data.hadoop.admin.web.WorkflowController.java

@RequestMapping(value = "/workflows/{path}", method = RequestMethod.POST)
public String upload(@PathVariable String path, @RequestParam MultipartFile file, ModelMap model,
        @RequestParam(defaultValue = "0") int startFile, @RequestParam(defaultValue = "20") int pageSize,
        @ModelAttribute("date") Date date, Errors errors) throws Exception {

    String originalFilename = file.getOriginalFilename();
    if (file.isEmpty()) {
        errors.reject("file.upload.empty", new Object[] { originalFilename },
                "File upload was empty for filename=[" + HtmlUtils.htmlEscape(originalFilename) + "]");
        list(model, startFile, pageSize);
        return "workflows";
    }//from   ww  w.  j a  v a  2 s  .  com

    try {
        FileInfo dest = workflowService.createFile(path + "/" + originalFilename);
        file.transferTo(workflowService.getResource(dest.getPath()).getFile());
        workflowService.publish(dest);
        model.put("uploaded", dest.getPath());
    } catch (IOException e) {
        errors.reject("file.upload.failed", new Object[] { originalFilename },
                "File upload failed for " + HtmlUtils.htmlEscape(originalFilename));
    } catch (Exception e) {
        String message = "File upload failed downstream processing for "
                + HtmlUtils.htmlEscape(originalFilename);
        if (logger.isDebugEnabled()) {
            logger.debug(message, e);
        } else {
            logger.info(message);
        }
        errors.reject("file.upload.failed.downstream", new Object[] { originalFilename }, message);
    }

    if (errors.hasErrors()) {
        list(model, startFile, pageSize);
        return "workflows";
    }

    return "redirect:workflows";

}

From source file:org.springframework.integration.http.DefaultInboundRequestMapper.java

@SuppressWarnings("unchecked")
private Object createPayloadFromMultipartRequest(MultipartHttpServletRequest multipartRequest) {
    Map<String, Object> payloadMap = new HashMap<String, Object>(multipartRequest.getParameterMap());
    Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
    for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {
        MultipartFile multipartFile = entry.getValue();
        if (multipartFile.isEmpty()) {
            continue;
        }/*from  w w w .  ja v a2 s. c o  m*/
        try {
            if (this.copyUploadedFiles) {
                File tmpFile = File.createTempFile("si_", null);
                multipartFile.transferTo(tmpFile);
                payloadMap.put(entry.getKey(), tmpFile);
                if (logger.isDebugEnabled()) {
                    logger.debug("copied uploaded file [" + multipartFile.getOriginalFilename()
                            + "] to temporary file [" + tmpFile.getAbsolutePath() + "]");
                }
            } else if (multipartFile.getContentType() != null
                    && multipartFile.getContentType().startsWith("text")) {
                String multipartFileAsString = this.multipartCharset != null
                        ? new String(multipartFile.getBytes(), this.multipartCharset)
                        : new String(multipartFile.getBytes());
                payloadMap.put(entry.getKey(), multipartFileAsString);
            } else {
                payloadMap.put(entry.getKey(), multipartFile.getBytes());
            }
        } catch (IOException e) {
            throw new IllegalArgumentException("Cannot read contents of multipart file", e);
        }
    }
    return Collections.unmodifiableMap(payloadMap);
}

From source file:org.vpac.web.controller.DataController.java

@RequestMapping(value = "/Upload", method = RequestMethod.POST)
//public String uploadFile(@RequestParam String timeSliceId, @RequestParam MultipartFile file, @RequestParam(required = false) String fileId, @RequestParam(required = false) String count, ModelMap model) throws IOException {
public String uploadFile(@Valid FileRequest fileRequest, ModelMap model) throws Exception {

    log.info("File Upload");
    log.debug("Timeslice ID: {}", fileRequest.getTimeSliceId());
    log.debug("Task ID: {}", fileRequest.getTaskId());

    Upload upload;/* w  ww  . j av  a  2  s  .  c  o m*/
    if (fileRequest.getTaskId() == null || fileRequest.getTaskId().isEmpty()) {
        upload = new Upload(fileRequest.getTimeSliceId());
        uploadDao.create(upload);
        log.debug("Create UploadFileId: {}", upload.getFileId());
    } else {
        upload = uploadDao.retrieve(fileRequest.getTaskId());
        if (upload == null) {
            // Capture if band not exist
            throw new ResourceNotFoundException(
                    String.format("Upload with task ID = \"%s\" not found.", fileRequest.getTaskId()));
        }
        log.debug("Retrieve UploadFileId: {}", upload.getFileId());
    }
    Path fileIdDir = uploadUtil.getDirectory(upload).toAbsolutePath();
    uploadUtil.createDirectory(upload);

    for (MultipartFile file : fileRequest.getFiles()) {
        Path target = fileIdDir.resolve(file.getOriginalFilename());
        if (!file.isEmpty())
            file.transferTo(target.toFile());
    }

    model.addAttribute(ControllerHelper.RESPONSE_ROOT, new FileInfoResponse(upload.getFileId()));
    return "FileUploadSuccess";
}

From source file:ru.mystamps.web.support.beanvalidation.ImageFileValidator.java

@SuppressWarnings({ "PMD.ModifiedCyclomaticComplexity", "PMD.NPathComplexity" })
@Override/*from  w  ww. jav a 2s . com*/
public boolean isValid(MultipartFile file, ConstraintValidatorContext ctx) {

    if (file == null) {
        return true;
    }

    if (StringUtils.isEmpty(file.getOriginalFilename())) {
        return true;
    }

    if (file.isEmpty()) {
        return false;
    }

    String contentType = file.getContentType();
    if (!PNG_CONTENT_TYPE.equals(contentType) && !JPEG_CONTENT_TYPE.equals(file.getContentType())) {
        LOG.debug("Reject file with content type '{}'", contentType);
        return false;
    }

    try (InputStream stream = file.getInputStream()) {

        byte[] firstPart = readFourBytes(stream);
        if (firstPart == null) {
            LOG.warn("Failed to read 4 bytes from file");
            return false;
        }

        if (isJpeg(firstPart)) {
            return true;
        }

        if (doesItLookLikePng(firstPart)) {
            byte[] secondPart = readFourBytes(stream);
            if (isItReallyPng(secondPart)) {
                return true;
            }

            LOG.debug("Looks like file isn't a PNG image. First bytes: {} {}", formatBytes(firstPart),
                    formatBytes(secondPart));
            return false;
        }

        LOG.debug("Looks like file isn't an image. First bytes: {}", formatBytes(firstPart));
        return false;

    } catch (IOException e) {
        LOG.warn("Error during file type validation: {}", e.getMessage());
        return false;
    }
}

From source file:ru.mystamps.web.support.beanvalidation.NotEmptyFileValidator.java

@Override
public boolean isValid(MultipartFile file, ConstraintValidatorContext ctx) {

    if (file == null) {
        return true;
    }//from   w w w  .  jav a 2s  .  c  o  m

    if (StringUtils.isEmpty(file.getOriginalFilename())) {
        return true;
    }

    return !file.isEmpty();
}

From source file:ru.org.linux.spring.AddMessageForm.java

public AddMessageForm(HttpServletRequest request, Template tmpl)
        throws IOException, ScriptErrorException, ServletRequestBindingException {
    postIP = request.getRemoteAddr();/* www  . j  a  v a  2 s.  c  o  m*/

    noinfo = "1".equals(request.getParameter("noinfo"));
    sessionId = request.getParameter("session");
    preview = request.getParameter("preview") != null;
    if (!"GET".equals(request.getMethod())) {
        captchaResponse = request.getParameter("j_captcha_response");
        nick = request.getParameter("nick");
        password = request.getParameter("password");
        mode = request.getParameter("mode");
        title = request.getParameter("title");
        msg = request.getParameter("msg");
    }

    if (request.getParameter("group") == null) {
        throw new ScriptErrorException("missing group parameter");
    }

    guid = ServletRequestUtils.getRequiredIntParameter(request, "group");

    linktext = request.getParameter("linktext");
    url = request.getParameter("url");
    returnUrl = request.getParameter("return");
    tags = request.getParameter("tags");

    if (request instanceof MultipartHttpServletRequest) {
        MultipartFile multipartFile = ((MultipartRequest) request).getFile("image");
        if (multipartFile != null && !multipartFile.isEmpty()) {
            File uploadedFile = File.createTempFile("preview", "",
                    new File(tmpl.getObjectConfig().getPathPrefix() + "/linux-storage/tmp/"));
            image = uploadedFile.getPath();
            if ((uploadedFile.canWrite() || uploadedFile.createNewFile())) {
                try {
                    logger.debug("Transfering upload to: " + image);
                    multipartFile.transferTo(uploadedFile);
                } catch (Exception e) {
                    throw new ScriptErrorException("Failed to write uploaded file", e);
                }
            } else {
                logger.info("Bad target file name: " + image);
            }
        }
    }

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

    for (int i = 0; i < Poll.MAX_POLL_SIZE; i++) {
        String poll = request.getParameter("var" + i);

        if (poll != null) {
            pollList.add(poll);
        }
    }

    if (pollList.isEmpty()) {
        this.pollList = null;
    } else {
        this.pollList = ImmutableList.copyOf(pollList);
    }

    if (request.getParameter("multiSelect") != null) {
        multiSelect = true;
    }
}

From source file:ru.org.linux.user.AddPhotoController.java

@RequestMapping(value = "/addphoto.jsp", method = RequestMethod.POST)
@PreAuthorize("hasRole('ROLE_ANONYMOUS')")
public ModelAndView addPhoto(@RequestParam("file") MultipartFile file, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    if (file == null || file.isEmpty()) {
        return new ModelAndView("addphoto", "error", "  ");
    }/*w  w  w  .  j a v a  2s.c  om*/

    try {
        File uploadedFile = File.createTempFile("userpic", "",
                new File(configuration.getPathPrefix() + "/linux-storage/tmp/"));

        file.transferTo(uploadedFile);

        UserService.checkUserpic(uploadedFile);
        String extension = ImageInfo.detectImageType(uploadedFile);

        Random random = new Random();

        String photoname;
        File photofile;

        do {
            photoname = Integer.toString(AuthUtil.getCurrentUser().getId()) + ':' + random.nextInt() + '.'
                    + extension;
            photofile = new File(configuration.getHTMLPathPrefix() + "/photos", photoname);
        } while (photofile.exists());

        if (!uploadedFile.renameTo(photofile)) {
            logger.warn("Can't move photo to " + photofile);
            throw new ScriptErrorException("Can't move photo: internal error");
        }

        userDao.setPhoto(AuthUtil.getCurrentUser(), photoname);

        logger.info("? ?  "
                + AuthUtil.getCurrentUser().getNick());

        return new ModelAndView(new RedirectView(UriComponentsBuilder
                .fromUri(PROFILE_NOCACHE_URI_TEMPLATE.expand(AuthUtil.getCurrentUser().getNick()))
                .queryParam("nocache", Integer.toString(random.nextInt()) + "=").build().encode().toString()));
    } catch (IOException ex) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return new ModelAndView("addphoto", "error", ex.getMessage());
    } catch (BadImageException ex) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return new ModelAndView("addphoto", "error", ex.getMessage());
    } catch (UserErrorException ex) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return new ModelAndView("addphoto", "error", ex.getMessage());
    }
}