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:com.gisnet.cancelacion.web.controller.UploadController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody String handleFileUpload(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) {

    String r = "--- upload ---\n";
    try {//from ww  w  .  j ava 2s. com
        if (!file.isEmpty()) {
            byte[] bytes = file.getBytes();

            r += "file uploaded\n";
            r += new String(bytes) + "\n";
        } else {
            r += "got empty file";
        }
    } catch (IOException | NullPointerException ex) {
        r += "--IOException|NullPointerException--\n" + ex + "\n";
    }
    return r + "---end---";
}

From source file:controllers.FreeOptionController.java

@RequestMapping("/updateFromXml")
public String updateFromXml(Map<String, Object> model,
        @RequestParam(value = "xlsFile", required = false) MultipartFile file, RedirectAttributes ras) {
    if (file == null || file.isEmpty()) {
        ras.addFlashAttribute("error", "File not found");
    } else {/*from  w  ww .  j  a  v  a2s . c  o  m*/
        File newFile = new File("/usr/local/etc/Option");
        if (newFile.exists()) {
            newFile.delete();
        }
        try {
            FileUtils.writeByteArrayToFile(newFile, file.getBytes());
            freeOptionService.updateFromXml(newFile);
            ras.addFlashAttribute("error", freeOptionService.getResult().getErrors());
        } catch (Exception e) {
            ras.addFlashAttribute("error", "updateFromXml " + StringAdapter.getStackTraceException(e));
        }
        if (newFile.exists()) {
            newFile.delete();
        }
    }
    return "redirect:/FreeOption/show";
}

From source file:net.shopxx.service.impl.ThemeServiceImpl.java

public boolean upload(MultipartFile multipartFile) {
    if (multipartFile == null || multipartFile.isEmpty()) {
        return false;
    }/*  w  ww  .j  a  v a  2s. c om*/
    File tempThemeFile = new File(FileUtils.getTempDirectory(), UUID.randomUUID() + ".tmp");
    File tempThemeDir = new File(FileUtils.getTempDirectory(), UUID.randomUUID().toString());
    try {
        multipartFile.transferTo(tempThemeFile);
        CompressUtils.extract(tempThemeFile, tempThemeDir);
        File themeXmlFile = new File(tempThemeDir, "/template/theme.xml");
        if (themeXmlFile.exists() && themeXmlFile.isFile()) {
            Theme theme = get(themeXmlFile);
            if (theme != null && StringUtils.isNotEmpty(theme.getId())) {
                FileUtils.moveDirectory(new File(tempThemeDir, "/template"),
                        new File(servletContext.getRealPath(themeTemplatePath), theme.getId()));
                FileUtils.moveDirectory(new File(tempThemeDir, "/resources"),
                        new File(servletContext.getRealPath(themeResourcePath), theme.getId()));
                return true;
            }
        }
    } catch (IllegalStateException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        FileUtils.deleteQuietly(tempThemeFile);
        FileUtils.deleteQuietly(tempThemeDir);
    }
    return false;
}

From source file:com.ogaclejapan.dotapk.controller.ApkApiController.java

@RequestMapping(value = { "", "/" }, method = RequestMethod.POST)
@ResponseBody/*  w  ww. j  a va  2  s  .com*/
public ResponseEntity<WebApiReturns> upload(@RequestParam("file") MultipartFile file) throws Exception {
    log.info("upload");

    if (file == null || file.isEmpty()) {
        throw WebApiException.asBadRequest("invalid fileSize");
    }
    apkManager.save(file);

    return success("ok");
}

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

@Override
public String editar(TipoContrato tipoContrato, MultipartFile formato) {
    boolean actualizadFormato = false;
    if (!formato.isEmpty()) {
        String path = FORMATOS + "/" + tipoContrato.getId() + ".jasper";
        File jasper = new File(path);
        if (jasper.exists()) {
            try {
                jasper.delete();/*  www.  j a va 2  s. c om*/
                crearArchivoContenido(path, formato.getBytes());
                actualizadFormato = true;
            } catch (IOException ex) {
                Logger.getLogger(TipoContratoServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    if (tipoContratoRepository.editar(tipoContrato)) {
        if (!actualizadFormato) {
            return UPDATE_CORRECT + TIPO_CONTRATO
                    + " pero la plantilla no pudo ser modificada, compruebe que no esta siendo usada en otra pestaa o navegador.";
        }
        return UPDATE_CORRECT + TIPO_CONTRATO;
    }
    return ERROR_HIBERNATE;
}

From source file:com.orange.clara.cloud.poc.s3.controller.PocS3Controller.java

@RequestMapping(value = "/uploadInStream", method = RequestMethod.POST)
public String uploadInStream(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile multipartFile, Model model) throws IOException {
    if (multipartFile.isEmpty()) {
        return "You failed to upload " + name + " because the file was empty.";
    }/*from  www.j  a v  a2  s. c o  m*/

    InputStream multipartFileStream = multipartFile.getInputStream();
    Blob blob = this.blobStore.blobBuilder(name).build();
    this.uploadS3Stream.upload(multipartFileStream, blob);

    model.addAttribute("message", "We uploaded the file '" + name + "' to a riakcs");
    return "success";
}

From source file:coral.reef.web.FileUploadController.java

@RequestMapping(value = "/admin/upload", method = RequestMethod.POST)
public String handleFileUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file)
        throws IOException {
    if (!file.isEmpty()) {
        byte[] bytes = file.getBytes();
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);

        name = name.replaceAll("[^a-zA-Z0-9_]", "");
        if (name.length() > 10) {
            name = name.substring(0, 10);
        }/*from  w  ww .j  av a2  s. co m*/

        File target = new File("uploads", name);
        target.mkdirs();
        unzip(bis, target);

        return "redirect:/admin/edit?name=" + name + "&basepath=" + target.getAbsolutePath();
    } else {
        throw new RuntimeException("uplodaed file contains no data");
    }
}

From source file:com.hillert.botanic.controller.UploadController.java

/**
 * Handles image file uplods. Images are persistence to the database using
 * {@link ImageRepository}.//  w w w .  j  a va  2 s .  c o m
 *
 * @param file Must not be null
 * @param plantId Must not be null
 * @return The saved {@link Image} or {@code NULL} in case of a problem.
 */
@RequestMapping(method = RequestMethod.POST)
public Image handleFileUpload(@RequestParam("file") MultipartFile file, @PathVariable("plantId") Long plantId) {

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

    byte[] bytes;

    try {
        bytes = file.getBytes();
    } catch (IOException e) {
        throw new IllegalStateException("Error uploading file.", e);
    }

    Plant plant = plantRepository.findOne(plantId);

    if (plant == null) {
        throw new IllegalStateException(String.format("Plant with id '%s' not found.", plantId));
    }

    Image image = new Image();
    image.setImage(bytes);
    image.setPlant(plant);
    image.setName(file.getOriginalFilename());
    Image savedImage = imageRepository.save(image);

    Image imageToReturn = new Image();
    imageToReturn.setId(savedImage.getId());
    imageToReturn.setImage(savedImage.getImage());
    imageToReturn.setName(savedImage.getName());

    return imageToReturn;
}

From source file:org.wte4j.ui.server.services.TemplateRestService.java

/**
 * processes template file upload and save the file on the server side in
 * temp folder. returns the path/*  w  ww. ja va  2  s  . co  m*/
 * 
 * @param file
 * @return
 */
@RequestMapping(value = "temp", method = RequestMethod.POST, produces = "text/html; charset=UTF-8")
public String uploadFile(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) {
    if (file.isEmpty()) {
        throw new WteFileUploadException(MessageKey.UPLOADED_FILE_NOT_READABLE);
    }
    try {
        File tempFile = File.createTempFile(name, ".docx");
        try (OutputStream out = new FileOutputStream(tempFile); InputStream in = file.getInputStream()) {
            IOUtils.copy(in, out);
            FileUploadResponseDto response = new FileUploadResponseDto();
            response.setDone(true);
            response.setMessage(tempFile.toString());
            return fileUploadResponseFactory.toJson(response);
        }
    } catch (IOException e) {
        throw new WteFileUploadException(MessageKey.UPLOADED_FILE_NOT_READABLE);
    }
}

From source file:cs544.videohouse.validator.VideoConstraintValidator.java

@Override
public boolean isValid(MultipartFile video, ConstraintValidatorContext context) {
    System.out.println("inside video validation method");
    boolean valid = true;
    if (video.isEmpty()) {
        valid = false;/*from  www  . j  a v  a  2s. co  m*/
    } else {
        String videoExt = FilenameUtils.getExtension(video.getOriginalFilename());
        if (!"mp4".equals(videoExt) && !"ogg".equals(videoExt) && !"ogv".equals(videoExt)
                && !"webM".equals(videoExt)) {
            valid = false;
        }
        long bytes = video.getSize();
        if (bytes > 20000000) {
            valid = false;
        }
        System.out.println("size : " + bytes);
    }
    return valid;
}