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.jahia.modules.webflow.showcase.JobApplication.java

public void setCoverLetter(MultipartFile coverLetter) throws IOException {
    if (coverLetter != null && !coverLetter.isEmpty()) {
        this.coverLetter = copy(coverLetter);
    }// www  .j a  v a 2 s  . c o m
}

From source file:org.jodconverter.sample.springboot.ConverterController.java

@PostMapping("/converter")
public Object convert(@RequestParam("inputFile") final MultipartFile inputFile,
        @RequestParam(name = "outputFormat", required = false) final String outputFormat,
        final RedirectAttributes redirectAttributes) {

    if (inputFile.isEmpty()) {
        redirectAttributes.addFlashAttribute(ATTRNAME_ERROR_MESSAGE, "Please select a file to upload.");
        return ON_ERROR_REDIRECT;
    }//  w  w w. j a  v  a  2  s . co m

    if (StringUtils.isBlank(outputFormat)) {
        redirectAttributes.addFlashAttribute(ATTRNAME_ERROR_MESSAGE, "Please select an output format.");
        return ON_ERROR_REDIRECT;
    }

    // Here, we could have a dedicated service that would convert document
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

        final DocumentFormat targetFormat = DefaultDocumentFormatRegistry.getFormatByExtension(outputFormat);
        converter.convert(inputFile.getInputStream())
                .as(DefaultDocumentFormatRegistry
                        .getFormatByExtension(FilenameUtils.getExtension(inputFile.getOriginalFilename())))
                .to(baos).as(targetFormat).execute();

        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(targetFormat.getMediaType()));
        headers.add("Content-Disposition",
                "attachment; filename=" + FilenameUtils.getBaseName(inputFile.getOriginalFilename()) + "."
                        + targetFormat.getExtension());
        return new ResponseEntity<>(baos.toByteArray(), headers, HttpStatus.OK);

    } catch (OfficeException | IOException e) {
        redirectAttributes.addFlashAttribute(ATTRNAME_ERROR_MESSAGE,
                "Unable to convert the file " + inputFile.getOriginalFilename() + ". Cause: " + e.getMessage());
    }

    return ON_ERROR_REDIRECT;
}

From source file:ch.ralscha.extdirectspring_itest.FileUploadController.java

@ExtDirectMethod(value = ExtDirectMethodType.FORM_POST, group = "itest_upload", event = "test", entryClass = String.class, synchronizeOnSession = true)
@RequestMapping(value = "/test", method = RequestMethod.POST)
public void uploadTest(HttpServletRequest request, @RequestParam("fileUpload") MultipartFile file,
        final HttpServletResponse response, @Valid User user, BindingResult result) throws IOException {

    ExtDirectResponseBuilder builder = new ExtDirectResponseBuilder(request, response);

    if (file != null && !file.isEmpty()) {
        builder.addResultProperty("fileContents", new String(file.getBytes()));
        builder.addResultProperty("fileName", file.getOriginalFilename());
    }//from  w w  w .j  av  a2s.  c  o  m
    builder.addErrors(result);
    builder.addResultProperty("name", user.getName());
    builder.addResultProperty("firstName", user.getFirstName());
    builder.addResultProperty("age", user.getAge());
    builder.addResultProperty("email", user.getEmail());

    builder.successful();
    builder.buildAndWrite();
}

From source file:service.AuthorService.java

public ServiceResult registration(Author author, String password, String password2, MultipartFile[] files)
        throws IOException {
    if (author != null) {
        author.setActiveInt(1);//from w  w w .  j  av a 2s.c  o m
    }
    ServiceResult result = userService.registration(author, password, password2);
    if (!result.hasErrors() && files != null) {
        for (MultipartFile file : files) {
            if (file != null && !file.isEmpty()) {
                AuthorFile fileEnt = new AuthorFile();
                fileEnt.setAuthor(author);
                saveFile(fileEnt, file);
            }
        }
        userService.changeRights(author.getUserId(), Rights.getAuthorDefRights());
        List<Branch> lst = branchDao.search(null, null, null);
        List<Long> lslt = new ArrayList();
        for (Branch brn : lst) {
            lslt.add(brn.getBranchId());
        }
        changeRoleForAuthor(author.getUserId(), lslt);
    }
    return result;
}

From source file:csns.web.validator.AssignmentValidator.java

public void validate(Assignment assignment, MultipartFile uploadedFile, Errors errors) {
    validate(assignment, errors);//from  w w  w .  j ava  2 s . c  om

    if (!assignment.isOnline() && assignment.getDescription().getType() == ResourceType.FILE
            && assignment.getDescription().getFile() == null
            && (uploadedFile == null || uploadedFile.isEmpty()))
        errors.rejectValue("description.file", "error.field.required");
}

From source file:edu.wisc.doit.tcrypt.controller.EncryptController.java

@RequestMapping(value = "/encryptFile", method = RequestMethod.POST)
public ModelAndView encryptFile(@RequestParam("fileToEncrypt") MultipartFile file,
        @RequestParam("selectedServiceName") String serviceName, HttpServletResponse response)
        throws Exception {
    if (file.isEmpty()) {
        ModelAndView modelAndView = encryptTextInit();
        modelAndView.addObject("selectedServiceName", serviceName);
        return modelAndView;
    }//  ww  w.j  av a2 s  .c om

    final FileEncrypter fileEncrypter = this.getFileEncrypter(serviceName);
    final String filename = FilenameUtils.getName(file.getOriginalFilename());

    response.setHeader("Content-Type", "application/x-tar");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + ".tar" + "\"");

    final long size = file.getSize();
    try (final InputStream inputStream = file.getInputStream();
            final ServletOutputStream outputStream = response.getOutputStream()) {

        fileEncrypter.encrypt(filename, (int) size, inputStream, outputStream);
    }

    return null;
}

From source file:equipeDFK.sistemaX.controller.ControllerAgenda.java

/**
 * Mtodo que recebe uma requisio para importar os feriados,
 * ento ler o arquivo CSV e depois persistir os dados no banco
 * @param arquivoCSV//from  w  w w. j a  v  a 2  s.c o m
 * @param sobrescrever
 * @param req
 * @return String
 * @throws SQLException 
 */
@RequestMapping("openCSV")
public String OpenCSV(MultipartFile arquivoCSV, boolean sobrescrever, HttpServletRequest req)
        throws SQLException {
    GerenciadorDeFeriado gf = new GerenciadorDeFeriado();
    if (!arquivoCSV.isEmpty()) {
        try {
            byte[] b = arquivoCSV.getBytes();
            String caminho = req.getServletContext().getRealPath("/") + arquivoCSV.getOriginalFilename();
            System.out.println(caminho);
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(caminho)));
            stream.write(b);
            stream.close();
            OpenCSV opencsv = new OpenCSV();
            if (sobrescrever) {

            } else {

            }
            gf.importaferiado(opencsv.lerCSV(new File(caminho)), sobrescrever);
            List eventos = gf.listar();
            eventos.stream().forEach((evento) -> {
                System.out.println(evento);
            });
            req.getSession().setAttribute("feriados", eventos);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return "managerHoliday";
}

From source file:com.groupon.odo.controllers.BackupController.java

/**
 * Restore backup data//from  ww w. jav a  2  s . c  om
 *
 * @param fileData - json file with restore data
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/api/backup", method = RequestMethod.POST)
public @ResponseBody Backup processBackup(@RequestParam("fileData") MultipartFile fileData) throws Exception {
    // Method taken from: http://spring.io/guides/gs/uploading-files/
    if (!fileData.isEmpty()) {
        try {
            byte[] bytes = fileData.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(new File("backup-uploaded.json")));
            stream.write(bytes);
            stream.close();

        } catch (Exception e) {
        }
    }
    File f = new File("backup-uploaded.json");
    BackupService.getInstance().restoreBackupData(new FileInputStream(f));
    return BackupService.getInstance().getBackupData();
}

From source file:net.solarnetwork.node.setup.web.NodeCertificatesController.java

/**
 * Import a certificate reply (signed certificate chain).
 * //from  w w w  .  j av a 2  s.c  o m
 * @param file
 *        the CSR file to import
 * @return the destination view
 * @throws IOException
 *         if an IO error occurs
 */
@RequestMapping(value = "/import", method = RequestMethod.POST)
public String importSettings(@RequestParam(value = "file", required = false) MultipartFile file,
        @RequestParam(value = "text", required = false) String text) throws IOException {
    String pem = text;
    if (file != null && !file.isEmpty()) {
        pem = FileCopyUtils.copyToString(new InputStreamReader(file.getInputStream(), "UTF-8"));
    }
    pkiService.saveNodeSignedCertificate(pem);
    return "redirect:/certs";
}