Example usage for org.springframework.web.multipart MultipartFile getBytes

List of usage examples for org.springframework.web.multipart MultipartFile getBytes

Introduction

In this page you can find the example usage for org.springframework.web.multipart MultipartFile getBytes.

Prototype

byte[] getBytes() throws IOException;

Source Link

Document

Return the contents of the file as an array of bytes.

Usage

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

/**
 * Set the content with file or with provided link
 *
 * @param data the file//from   ww w.j  a v  a  2  s .com
 * @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);
    }
}

From source file:org.fao.geonet.api.records.attachments.FilesystemStore.java

@Override
public MetadataResource putResource(ServiceContext context, String metadataUuid, MultipartFile file,
        MetadataResourceVisibility visibility) throws Exception {
    canEdit(context, metadataUuid);/*from   w ww  . j a v a  2s.com*/
    Path filePath = getPath(metadataUuid, visibility, file.getOriginalFilename());

    BufferedOutputStream stream = new BufferedOutputStream(Files.newOutputStream(filePath));
    byte[] bytes = file.getBytes();
    stream.write(bytes);
    stream.close();

    return getResourceDescription(metadataUuid, visibility, filePath);
}

From source file:org.fenixedu.ulisboa.specifications.ui.evaluation.config.managemarksheetsettings.MarkSheetSettingsController.java

@RequestMapping(value = _UPDATETEMPLATEFILE_URI + "{oid}", method = RequestMethod.POST)
public String updateTemplateFile(@PathVariable("oid") MarkSheetSettings markSheetSettings,
        @RequestParam(value = "templateFile", required = true) MultipartFile templateFile, Model model,
        RedirectAttributes redirectAttributes) {

    setMarkSheetSettings(markSheetSettings, model);

    try {/*from w  ww  .  ja va 2  s .c o m*/
        markSheetSettings.editTemplateFile(FilenameUtils.getName(templateFile.getOriginalFilename()),
                templateFile.getBytes());

        return redirect(READ_URL + "/" + markSheetSettings.getExternalId(), model, redirectAttributes);

    } catch (Exception de) {

        addErrorMessage(de.getLocalizedMessage(), model);

        return updateTemplateFile(markSheetSettings, model);

    }
}

From source file:org.fenixedu.ulisboa.specifications.ui.evaluation.managemarksheet.administrative.CompetenceCourseMarkSheetController.java

@RequestMapping(value = _IMPORT_EXCEL_URI + "{oid}", method = RequestMethod.POST)
public String importExcel(@PathVariable("oid") final CompetenceCourseMarkSheet competenceCourseMarkSheet,
        @RequestParam(value = "file", required = true) MultipartFile markSheetFile, final Model model,
        final RedirectAttributes redirectAttributes) throws IOException {

    CompetenceCourseMarkSheetBean bean = null;
    try {/*from w w  w. ja  v  a 2s.c o  m*/
        bean = MarkSheetImportExportService.importFromXLSX(competenceCourseMarkSheet,
                FilenameUtils.getName(markSheetFile.getOriginalFilename()), markSheetFile.getBytes());
        bean.updateEnrolmentEvaluations();

        addInfoMessage(
                ULisboaSpecificationsUtil.bundle("label.event.evaluation.manageMarkSheet.importExcel.success"),
                model);

    } catch (Exception e) {
        addErrorMessage(e.getLocalizedMessage(), model);
    }

    setCompetenceCourseMarkSheet(competenceCourseMarkSheet, model);
    setCompetenceCourseMarkSheetBean(
            bean == null ? new CompetenceCourseMarkSheetBean(competenceCourseMarkSheet) : bean, model);

    return jspPage("updateevaluations");

}

From source file:org.fenixedu.ulisboa.specifications.ui.evaluation.managemarksheet.teacher.CompetenceCourseMarkSheetController.java

@RequestMapping(value = _IMPORT_EXCEL_URI + "{executionCourseId}/{oid}", method = RequestMethod.POST)
public String importExcel(@PathVariable("oid") final CompetenceCourseMarkSheet competenceCourseMarkSheet,
        @RequestParam(value = "file", required = true) MultipartFile markSheetFile, final Model model,
        final RedirectAttributes redirectAttributes) throws IOException {

    CompetenceCourseMarkSheetBean bean = null;
    try {/*  w w w .  j  ava 2  s  .co  m*/
        bean = MarkSheetImportExportService.importFromXLSX(competenceCourseMarkSheet,
                FilenameUtils.getName(markSheetFile.getOriginalFilename()), markSheetFile.getBytes());
        bean.updateEnrolmentEvaluations();

        addInfoMessage(
                ULisboaSpecificationsUtil.bundle("label.event.evaluation.manageMarkSheet.importExcel.success"),
                model);

    } catch (Exception e) {
        addErrorMessage(e.getLocalizedMessage(), model);
    }

    setCompetenceCourseMarkSheet(competenceCourseMarkSheet, model);
    setCompetenceCourseMarkSheetBean(
            bean == null ? new CompetenceCourseMarkSheetBean(competenceCourseMarkSheet) : bean, model);

    return jspPage("updateevaluations");

}

From source file:org.flowable.app.rest.idm.IdmProfileResource.java

@ResponseStatus(value = HttpStatus.OK)
@RequestMapping(value = "/profile-picture", method = RequestMethod.POST, produces = "application/json")
public void uploadProfilePicture(@RequestParam("file") MultipartFile file) {
    try {//from w  w  w .j a v a2 s  .c  o  m
        profileService.uploadProfilePicture(file.getContentType(), file.getBytes());
    } catch (IOException e) {
        throw new InternalServerErrorException(e.getMessage(), e);
    }
}

From source file:org.geowebcache.sqlite.OperationsRest.java

private File handleFileUpload(MultipartFile uploadedFile, File workingDirectory) throws Exception {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Handling file upload.");
    }/*from   w  ww  .j ava 2s  .c om*/
    // getting the uploaded file content
    File outputFile = new File(workingDirectory, UUID.randomUUID().toString());
    byte[] bytes = uploadedFile.getBytes();
    try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(outputFile))) {
        stream.write(bytes);
    }
    return outputFile;
}

From source file:org.group2.webapp.web.mvc.ctrl.UploadController.java

@PostMapping("/upload")
public @ResponseBody String uploadFileHandlerPOST(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) {

    String actualPath = servletContext.getRealPath("");
    String fileLocation = actualPath + File.separator + "evidents";

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

            File dir = new File(fileLocation);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            File serverFile = new File(dir.getAbsolutePath() + File.separator + name);

            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();

            logger.info("Saved to: " + serverFile.getAbsolutePath());

            return "You successfully uploaded file=" + name;

        } catch (Exception e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name + " because the file was empty.";
    }
}

From source file:org.group2.webapp.web.mvc.ctrl.UploadController.java

@PostMapping("/multiupload")
public @ResponseBody String uploadMultipleFileHandler(@RequestParam("evidenceFiles") MultipartFile[] files) {

    //        if (files.length != names.length) {
    //            return "Mandatory information missing";
    //        }//from w  w w  .ja  v  a 2 s. c om
    String name;

    String message = "";
    for (int i = 0; i < files.length; i++) {
        MultipartFile file = files[i];
        try {
            byte[] bytes = file.getBytes();

            long time = System.currentTimeMillis();
            java.sql.Timestamp timestmp = new java.sql.Timestamp(time);
            name = "evidence" + i + "_" + timestmp.getTime();

            logger.info(FilenameUtils.getExtension(file.getOriginalFilename()));

            // Creating the directory to store file
            String actualPath = servletContext.getRealPath("");
            String fileLocation = actualPath + File.separator + "evidents";

            File dir = new File(fileLocation);
            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("Saved to: " + serverFile.getAbsolutePath());

            message = message + "You successfully uploaded file=" + name;

        } catch (Exception e) {
            return "You failed to upload evidents" + e.getMessage();
        }
    }
    return message;
}

From source file:org.jasig.portlet.attachment.mvc.LocalAttachmentController.java

@RequestMapping(value = "/content/attach/local.json", method = RequestMethod.POST)
public ModelAndView uploadForm(@RequestParam(value = "qqfile") MultipartFile file,
        HttpServletRequest servletRequest) throws IOException {
    final Map<String, String> model = new HashMap<String, String>();
    final String user = (String) servletRequest.getSession()
            .getAttribute(AttachmentsController.REMOTE_USER_ATTR);
    final HttpServletRequest request = new AttachmentServletRequestWrapper(servletRequest, user);

    if (file != null) {
        Attachment attachment = generateAttachment(file, request);
        attachment = attachmentService.save(attachment, request.getRemoteUser());
        if (attachment.getId() > 0) {
            String path = getAttachmentAbsolutePath(attachment, request);
            FileUtil.write(path, file.getBytes());
            model.put("id", Long.toString(attachment.getId()));
            model.put("guid", attachment.getGuid());
            model.put("path", attachment.getPath());
            model.put("filename", attachment.getFilename());
            model.put("success", "true");
        }/*ww w .j  av  a2  s .  co m*/
    }

    return new ModelAndView("jsonView", model);
}