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.jtalks.common.web.validation.ImageDimensionValidator.java

/**
 * Validate object with {@link ImageDimension} annotation.
 *
 * @param multipartFile image that user want upload as avatar
 * @param context       validation context
 * @return {@code true} if validation successfull or false if fails
 *//*from  w  w  w  .jav a 2  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;
    }
    Image image;
    try {
        image = ImageIO.read(multipartFile.getInputStream());
    } catch (Exception e) {
        return false;
    }
    return (image == null) ? false : image.getWidth(null) == imageWidth && image.getHeight(null) == imageHeight;
}

From source file:se.omegapoint.facepalm.client.controllers.ImageController.java

@RequestMapping(value = "/postImage", method = RequestMethod.POST)
public String postImage(final @RequestParam("title") String title,
        final @RequestParam("file") MultipartFile file) {
    if (!file.isEmpty()) {
        try {//  www.j a  va  2s.co m
            final byte[] data = notNull(file.getBytes());
            imageAdapter.addImage(new ImageUpload(title, data));
        } catch (IOException e) {
            throw new IllegalArgumentException("Illegal file upload!");
        }
    }
    return "redirect:/";
}

From source file:gg.server.MailController.java

@RequestMapping(method = RequestMethod.POST)
public ModelAndView handleEmailUpload(@RequestParam("email") MultipartFile email) {
    if (!email.isEmpty()) {
        try {//from   w w  w .ja  va2s  . c  om
            byte[] bytes = email.getBytes();
            log.debug("Got POST {} bytes", bytes.length);
            mailer.sendMail(bytes);
        } catch (IOException e) {
            return errorPage("Failed receiving email data", e);
        } catch (RuntimeException e) {
            return errorPage("Failed sending mail", e);
        }
    }
    return success;
}

From source file:com.vtxii.smallstuff.etl.fileuploader.FileUploaderController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody String handleFileUpload(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) {
    if (false == file.isEmpty()) {
        try {/*from   w  w w  . j  a  v  a 2  s . c  om*/
            // See if the file exists. If it does then another user
            // has uploaded a file of the same name at the same time
            // and it has not yet been processed.
            File newFile = new File(name);
            if (true == newFile.exists()) {
                String msg = "fail: file \"" + name + "\" exists and hasn't been processed";
                logger.error(msg);
                return msg;
            }

            // Write the file (this should be to the landing directory)
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(newFile));
            stream.write(bytes);
            stream.close();

            // Process the file
            LandingManager.process(newFile, processor, null);

            return "success: loaded " + name;
        } catch (Exception e) {
            String msg = "fail: file \"" + name + "\" with error " + e.getMessage();
            logger.error(msg);
            return msg;
        }
    } else {
        return "fail: file \"" + name + "\" empty";
    }
}

From source file:com.persistent.cloudninja.validator.LogoFileDTOValidator.java

/**
 * validates the multipart file./*from   w w w  .ja v  a2 s . co m*/
 * 
 * @param target : LogoFile object.
 * @param errors : stores and exposes validation errors.
 * 
 */
@Override
public void validate(Object target, Errors errors) {
    LogoFileDTO logoFile = (LogoFileDTO) target;
    MultipartFile file = logoFile.getFile(); // file should be of gif, png, bmp, jpeg, jpg type
    if (file.isEmpty()) {
        errors.rejectValue("file", "Invalid file", "File cannot be empty");
    } else if (!(file.getOriginalFilename().endsWith(".gif") | file.getOriginalFilename().endsWith(".png")
            | file.getOriginalFilename().endsWith(".bmp") | file.getOriginalFilename().endsWith(".jpeg")
            | file.getOriginalFilename().endsWith(".jpg"))) {
        errors.rejectValue("file", "Invalid file", "File should be a valid gif,png, bmp, jpeg or jpg file.");
    } else if (logoFile.getFile().getSize() > 200 * 1024) {
        errors.rejectValue("file", "Invalid file", "File size should be less then 200KB.");
    }
}

From source file:mx.com.quadrum.service.impl.TipoContratoServiceImpl.java

@Override
public String agregar(TipoContrato tipoContrato, MultipartFile formato) {

    if (!formato.isEmpty()) {
        String path = FORMATOS + tipoContrato.getNombre() + ".jasper";
        try {/*from   w w w .  j a v a2 s .c  o m*/
            if (crearArchivoContenido(path, formato.getBytes())) {
                if (tipoContratoRepository.agregar(tipoContrato)) {
                    File file = new File(path);
                    file.renameTo(new File(FORMATOS + tipoContrato.getId() + ".jasper"));
                    return ADD_CORRECT + TIPO_CONTRATO;
                }
                return ERROR_HIBERNATE;
            } else {
                return "Ups!...#No fue posible guardar el formato, intente mas tarde.";
            }
        } catch (IOException ex) {
            Logger.getLogger(TipoContratoServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return "Ups!...#Encontramos que el archivo que subio esta vacio.";

}

From source file:service.DelegateMessageService.java

public ServiceResult save(DelegateMessage message, MultipartFile[] files, Long orderIdFrom, Long orderIdTo,
        Type type) throws IOException {
    ServiceResult res = new ServiceResult();
    Order orderFrom = orderDao.find(orderIdFrom);
    Order orderTo = orderDao.find(orderIdTo);
    if (type.equals(Type.FROM_CHILD_TO_PARENT)) {
        orderFrom.setDesiredCost(message.getCost());
        orderDao.update(orderFrom);//from  w  w w  .ja v a2s  .co  m
    }
    message.setOrderFrom(orderFrom);
    message.setOrderTo(orderTo);
    message.setMessageDate(new Date());
    message.setInsertUser(authManager.getCurrentUser());
    validateSave(message, delegateMessageDao, res);
    if (!res.hasErrors()) {
        if (files != null) {
            for (MultipartFile file : files) {
                if (file != null && !file.isEmpty()) {
                    DelegateMessageFile fileEntity = new DelegateMessageFile();
                    fileEntity.setMessage(message);
                    fileService.saveNewFile(fileEntity, file);
                }
            }
        }
    }
    return res;
}

From source file:org.shareok.data.webserv.PlosWebController.java

@RequestMapping(value = "/plos/upload", method = RequestMethod.POST)
public ModelAndView plosUpload(@RequestParam("file") MultipartFile file) {

    if (!file.isEmpty()) {
        try {/*from  w ww  . j  ava2  s  .  c  o m*/
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            //                String rootPath = System.getProperty("catalina.home");
            //                File dir = new File(rootPath + File.separator + "tmpFiles");
            //                if (!dir.exists())
            //                    dir.mkdirs();
            // 
            //                // Create the file on server
            //                File serverFile = new File(dir.getAbsolutePath()
            //                        + File.separator + name);
            //                BufferedOutputStream stream = new BufferedOutputStream(
            //                        new FileOutputStream(serverFile));
            //                stream.write(bytes);
            //                stream.close();

            //                logger.info("Server File Location="
            //                        + serverFile.getAbsolutePath());
            System.out.println("The uploaded file name is " + file.getName() + "\n");
            ModelAndView model = new ModelAndView();
            model.setViewName("plosDataUpload");
            model.addObject("message", file.getOriginalFilename());

            return model;
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        return null;
    }
    return null;
}

From source file:uk.urchinly.wabi.ingest.UploadController.java

@RequestMapping(method = RequestMethod.POST, value = "/upload")
public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) {

    if (file.isEmpty()) {
        logger.debug("Upload file is empty.");
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Failed with empty file");
    }//from w  w w .j av  a2s.  c o m

    BufferedOutputStream outputStream = null;

    try {
        File outputFile = new File(appSharePath + "/" + file.getOriginalFilename());
        outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

        FileCopyUtils.copy(file.getInputStream(), outputStream);

        Asset asset = new Asset(file.getOriginalFilename(), file.getOriginalFilename(), (double) file.getSize(),
                file.getContentType(), Collections.emptyList());

        this.saveAsset(asset);
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Failed with error");
    } finally {
        IOUtils.closeQuietly(outputStream);
    }

    return ResponseEntity.ok("File accepted");
}

From source file:ru.mystamps.web.validation.jsr303.NotEmptyFileValidator.java

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

    if (file == null) {
        return true;
    }/*from  w  ww . ja  va  2  s  .c om*/

    return !file.isEmpty();
}