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

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

Introduction

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

Prototype

@Override
InputStream getInputStream() throws IOException;

Source Link

Document

Return an InputStream to read the contents of the file from.

Usage

From source file:org.egov.council.web.controller.CouncilPreambleController.java

@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(@Valid @ModelAttribute final CouncilPreamble councilPreamble, final Model model,
        @RequestParam final MultipartFile attachments, final BindingResult errors,
        final HttpServletRequest request, final RedirectAttributes redirectAttrs,
        @RequestParam String workFlowAction) {
    validatePreamble(councilPreamble, errors);
    if (errors.hasErrors()) {
        prepareWorkFlowOnLoad(model, councilPreamble);
        model.addAttribute(CURRENT_STATE, councilPreamble.getCurrentState().getValue());
        return COUNCILPREAMBLE_EDIT;
    }/*from   ww  w.  ja v a2 s .  com*/
    List<Boundary> wardIdsList = new ArrayList<>();

    String selectedWardIds = request.getParameter("wardsHiddenIds");

    if (StringUtils.isNotEmpty(selectedWardIds)) {
        String[] wardIds = selectedWardIds.split(",");

        for (String wrdId : wardIds) {
            if (StringUtils.isNotEmpty(wrdId))
                wardIdsList.add(boundaryService.getBoundaryById(Long.valueOf(wrdId)));
        }
    }
    councilPreamble.setWards(wardIdsList);

    if (attachments != null && attachments.getSize() > 0) {
        try {
            councilPreamble.setFilestoreid(
                    fileStoreService.store(attachments.getInputStream(), attachments.getOriginalFilename(),
                            attachments.getContentType(), CouncilConstants.MODULE_NAME));
        } catch (IOException e) {
            LOGGER.error("Error in loading Employee photo" + e.getMessage(), e);
        }
    }

    Long approvalPosition = 0l;
    String approvalComment = StringUtils.EMPTY;
    String message = StringUtils.EMPTY;
    String nextDesignation = "";
    String approverName = "";

    if (request.getParameter(APPROVAL_COMENT) != null)
        approvalComment = request.getParameter(APPROVAL_COMENT);
    if (request.getParameter(WORK_FLOW_ACTION) != null)
        workFlowAction = request.getParameter(WORK_FLOW_ACTION);
    if (request.getParameter(APPROVAL_POSITION) != null && !request.getParameter(APPROVAL_POSITION).isEmpty())
        approvalPosition = Long.valueOf(request.getParameter(APPROVAL_POSITION));
    if (request.getParameter("approverName") != null)
        approverName = request.getParameter("approverName");
    if (request.getParameter("nextDesignation") == null)
        nextDesignation = StringUtils.EMPTY;
    else
        nextDesignation = request.getParameter("nextDesignation");

    councilPreambleService.update(councilPreamble, approvalPosition, approvalComment, workFlowAction);
    if (null != workFlowAction) {
        if (CouncilConstants.WF_STATE_REJECT.equalsIgnoreCase(workFlowAction)) {
            message = getMessage("msg.councilPreamble.reject", nextDesignation, approverName, councilPreamble);
        } else if (CouncilConstants.WF_APPROVE_BUTTON.equalsIgnoreCase(workFlowAction)) {
            message = getMessage("msg.councilPreamble.success", nextDesignation, approverName, councilPreamble);
        } else if (CouncilConstants.WF_FORWARD_BUTTON.equalsIgnoreCase(workFlowAction)) {
            message = getMessage("msg.councilPreamble.forward", nextDesignation, approverName, councilPreamble);
        } else if (CouncilConstants.WF_PROVIDE_INFO_BUTTON.equalsIgnoreCase(workFlowAction)) {
            message = getMessage("msg.councilPreamble.moreInfo", nextDesignation, approverName,
                    councilPreamble);
        }
        redirectAttrs.addFlashAttribute(MESSAGE2, message);
    }
    return REDIRECT_COUNCILPREAMBLE_RESULT + councilPreamble.getId();
}

From source file:org.egov.infra.utils.ImageUtils.java

public static File compressImage(MultipartFile imageFile) throws IOException {
    return compressImage(imageFile.getInputStream(), imageFile.getOriginalFilename(), true);
}

From source file:org.egov.mrs.domain.service.MarriageRegistrationService.java

public FileStoreMapper addToFileStore(final MultipartFile file) {
    FileStoreMapper fileStoreMapper = null;
    try {//from w w  w .  j  a  va 2  s  .c  o m
        fileStoreMapper = fileStoreService.store(file.getInputStream(), file.getOriginalFilename(),
                file.getContentType(), MarriageConstants.FILESTORE_MODULECODE);
    } catch (final IOException e) {
        throw new ApplicationRuntimeException("Error occurred while getting inputstream", e);
    }
    return fileStoreMapper;
}

From source file:org.encuestame.mvc.page.FileUploadController.java

/**
 * Upload Profile for User Account./*from  ww  w  . j av  a2s  .  c  o  m*/
 * @param multipartFile
 * @return
 */
@PreAuthorize("hasRole('ENCUESTAME_USER')")
@RequestMapping(value = "/file/upload/profile", method = RequestMethod.POST)
public ModelAndView handleUserProfileFileUpload(@RequestParam("file") MultipartFile multipartFile) {
    ModelAndView mav = new ModelAndView(new MappingJackson2JsonView());
    if (!multipartFile.isEmpty()) {
        log.debug(multipartFile.getName());
        String orgName = multipartFile.getOriginalFilename();
        log.debug("org name " + orgName);
        //TODO: convert name to numbers, MD5 hash.
        String filePath = null;
        try {
            log.debug("getting file path for this user");
            filePath = getPictureService()
                    .getAccountUserPicturePath(getSecurityService().getUserAccount(getUserPrincipalUsername()));
            InputStream stream = multipartFile.getInputStream();
            try {
                //generate thumbnails
                thumbnailGeneratorEngine.generateThumbnails(PathUtil.DEFAUL_PICTURE_PREFIX, stream,
                        multipartFile.getContentType(), filePath);
            } catch (Exception e) {
                //e.printStackTrace();
                log.error(e);
            } finally {
                stream.close();
            }
            //TODO: after save image, we need relationship user with profile picture.
            //I suggest store ID on user account table, to retrieve easily future profile image.
            //BUG 102
        } catch (IllegalStateException e) {
            //e.printStackTrace();
            log.error("File uploaded failed:" + orgName);
        } catch (IOException e) {
            //e.printStackTrace();
            log.error("File uploaded failed:" + orgName);
        } catch (EnMeNoResultsFoundException e) {
            ///e.printStackTrace();
            log.error("File uploaded failed:" + orgName);
        } catch (EnmeFailOperation e) {
            //e.printStackTrace();
            log.error("File uploaded failed:" + orgName);
        }
        // Save the file here
        mav.addObject("status", "saved");
        mav.addObject("id", filePath);
    } else {
        mav.addObject("status", "failed");
    }
    return mav;
}

From source file:org.esupportail.pay.web.admin.PayEvtController.java

@RequestMapping(value = "/{id}/addLogoFile", method = RequestMethod.POST, produces = "text/html")
@PreAuthorize("hasPermission(#id, 'manage')")
public String addLogoFile(@PathVariable("id") Long id, UploadFile uploadFile, BindingResult bindingResult,
        Model uiModel, HttpServletRequest request) throws IOException {
    if (bindingResult.hasErrors()) {
        log.warn(bindingResult.getAllErrors());
        return "redirect:/admin/evts/" + id.toString();
    }//from  ww w  . j a  v a2s. com
    uiModel.asMap().clear();

    // get PosteCandidature from id                                                                                                                                                                                               
    PayEvt evt = PayEvt.findPayEvt(id);

    MultipartFile file = uploadFile.getLogoFile();

    // sometimes file is null here, but I don't know how to reproduce this issue ... maybe that can occur only with some specifics browsers ?                                                                                     
    if (file != null) {
        Long fileSize = file.getSize();
        //String contentType = file.getContentType();
        //String filename = file.getOriginalFilename();

        InputStream inputStream = file.getInputStream();
        //byte[] bytes = IOUtils.toByteArray(inputStream);                                                                                                                                            

        evt.getLogoFile().setBinaryFileStream(inputStream, fileSize);
        evt.getLogoFile().persist();
    }

    return "redirect:/admin/evts/" + id.toString();
}

From source file:org.exem.flamingo.web.filesystem.s3.S3BrowserServiceImpl.java

@Override
public void upload(String bucketName, String key, MultipartFile file) throws IOException {
    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentLength(file.getSize());
    PutObjectRequest request = new PutObjectRequest(bucketName, key, file.getInputStream(), metadata);
    this.s3.putObject(request);

}

From source file:org.fao.geonet.api.records.MetadataInsertDeleteApi.java

@ApiOperation(value = "Add a record from XML or MEF/ZIP file", notes = "Add record in the catalog by uploading files.", nickname = "insertFile")
@RequestMapping(method = { RequestMethod.POST, }, produces = { MediaType.APPLICATION_JSON_VALUE })
@ApiResponses(value = { @ApiResponse(code = 201, message = API_PARAM_REPORT_ABOUT_IMPORTED_RECORDS),
        @ApiResponse(code = 403, message = ApiParams.API_RESPONSE_NOT_ALLOWED_ONLY_EDITOR) })
@PreAuthorize("hasRole('Editor')")
@ResponseStatus(HttpStatus.CREATED)//www  .j a  v  a 2 s.  c  o  m
@ResponseBody
public SimpleMetadataProcessingReport insertFile(
        @ApiParam(value = API_PARAM_RECORD_TYPE, required = false, defaultValue = "METADATA") @RequestParam(required = false, defaultValue = "METADATA") final MetadataType metadataType,
        @ApiParam(value = "XML or MEF file to upload", required = false) @RequestParam(value = "file", required = false) MultipartFile[] file,
        @ApiParam(value = API_PARAM_RECORD_UUID_PROCESSING, required = false, defaultValue = "NOTHING") @RequestParam(required = false, defaultValue = "NOTHING") final MEFLib.UuidAction uuidProcessing,
        @ApiParam(value = API_PARAP_RECORD_GROUP, required = false) @RequestParam(required = false) final String group,
        @ApiParam(value = API_PARAM_RECORD_TAGS, required = false) @RequestParam(required = false) final String[] category,
        @ApiParam(value = API_PARAM_RECORD_VALIDATE, required = false) @RequestParam(required = false, defaultValue = "false") final boolean rejectIfInvalid,
        @ApiParam(value = "(XML file only) Publish record.", required = false) @RequestParam(required = false, defaultValue = "false") final boolean publishToAll,
        @ApiParam(value = "(MEF file only) Assign to current catalog.", required = false) @RequestParam(required = false, defaultValue = "false") final boolean assignToCatalog,
        @ApiParam(value = API_PARAM_RECORD_XSL, required = false, defaultValue = "_none_") @RequestParam(required = false, defaultValue = "_none_") final String transformWith,
        @ApiParam(value = API_PARAM_FORCE_SCHEMA, required = false) @RequestParam(required = false) String schema,
        @ApiParam(value = "(experimental) Add extra information to the record.", required = false) @RequestParam(required = false) final String extra,
        HttpServletRequest request) throws Exception {
    if (file == null) {
        throw new IllegalArgumentException(String.format("A file MUST be provided."));
    }
    SimpleMetadataProcessingReport report = new SimpleMetadataProcessingReport();
    if (file != null) {
        ServiceContext context = ApiUtils.createServiceContext(request);
        ApplicationContext applicationContext = ApplicationContextHolder.get();
        SettingManager settingManager = applicationContext.getBean(SettingManager.class);
        for (MultipartFile f : file) {
            if (MEFLib.isValidArchiveExtensionForMEF(f.getOriginalFilename())) {
                Path tempFile = Files.createTempFile("mef-import", ".zip");
                try {
                    FileUtils.copyInputStreamToFile(f.getInputStream(), tempFile.toFile());

                    MEFLib.Version version = MEFLib.getMEFVersion(tempFile);

                    List<String> ids = MEFLib.doImport(version == MEFLib.Version.V1 ? "mef" : "mef2",
                            uuidProcessing, transformWith, settingManager.getSiteId(), metadataType, category,
                            group, rejectIfInvalid, assignToCatalog, context, tempFile);
                    ids.forEach(e -> {
                        report.addMetadataInfos(Integer.parseInt(e),
                                String.format("Metadata imported with ID '%s'", e));

                        try {
                            triggerCreationEvent(request, e);
                        } catch (Exception e1) {
                            report.addError(e1);
                            report.addInfos(String.format(
                                    "Impossible to store event for '%s'. Check error for details.",
                                    f.getOriginalFilename()));
                        }

                        report.incrementProcessedRecords();
                    });
                } catch (Exception e) {
                    report.addError(e);
                    report.addInfos(String.format("Failed to import MEF file '%s'. Check error for details.",
                            f.getOriginalFilename()));
                } finally {
                    IO.deleteFile(tempFile, false, Geonet.MEF);
                }
            } else {
                Pair<Integer, String> pair = loadRecord(metadataType, Xml.loadStream(f.getInputStream()),
                        uuidProcessing, group, category, rejectIfInvalid, publishToAll, transformWith, schema,
                        extra, request);
                report.addMetadataInfos(pair.one(),
                        String.format("Metadata imported with UUID '%s'", pair.two()));

                triggerImportEvent(request, pair.two());

                report.incrementProcessedRecords();
            }
        }
    }
    report.close();
    return report;
}

From source file:org.fao.geonet.api.site.LogosApi.java

@ApiOperation(value = "Add a logo", notes = "", authorizations = {
        @Authorization(value = "basicAuth") }, nickname = "addLogo")
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
@PreAuthorize("hasRole('UserAdmin')")
@ApiResponses(value = { @ApiResponse(code = 201, message = "Logo added."),
        @ApiResponse(code = 403, message = ApiParams.API_RESPONSE_NOT_ALLOWED_ONLY_USER_ADMIN) })
@ResponseStatus(value = HttpStatus.CREATED)
@ResponseBody/*w ww  .ja v a  2  s  .  c o  m*/
public ResponseEntity addLogo(
        @ApiParam(value = "The logo image to upload") @RequestParam("file") MultipartFile[] file,
        @ApiParam(value = "Overwrite if exists", required = false) @RequestParam(defaultValue = "false", required = false) boolean overwrite)
        throws Exception {
    ApplicationContext appContext = ApplicationContextHolder.get();
    Path directoryPath;
    synchronized (this) {
        if (this.logoDirectory == null) {
            this.logoDirectory = Resources.locateHarvesterLogosDirSMVC(appContext);
        }
        directoryPath = this.logoDirectory;
    }

    for (MultipartFile f : file) {
        String fileName = f.getName();

        checkFileName(fileName);

        Path filePath = directoryPath.resolve(f.getOriginalFilename());
        if (Files.exists(filePath) && overwrite) {
            IO.deleteFile(filePath, true, "Deleting file");
            filePath = directoryPath.resolve(f.getOriginalFilename());
        } else if (Files.exists(filePath)) {
            throw new ResourceAlreadyExistException(f.getOriginalFilename());
        }

        filePath = Files.createFile(filePath);
        FileUtils.copyInputStreamToFile(f.getInputStream(), filePath.toFile());
    }
    return new ResponseEntity(HttpStatus.CREATED);
}

From source file:org.fenixedu.academic.ui.spring.controller.teacher.authorization.AuthorizationService.java

/***
 * Importation of teacher authorizations from a CSV file
 * /*www  .java 2s .co  m*/
 * @param period the period where to import
 * @param partFile the CSV file
 * @return
 */
public List<TeacherAuthorization> importCSV(ExecutionSemester period, MultipartFile partFile) {
    try {
        return importAuthorizations(period,
                csvService.readCsvFile(partFile.getInputStream(), ",", Charsets.UTF_8.toString()));
    } catch (IOException e) {
        throw new RuntimeException(message("teacher.authorizations.upload.parsing.failed"));
    }
}

From source file:org.fenixedu.ulisboa.specifications.ui.curricularrules.manageanycurricularcourseexceptionsconfiguration.AnyCurricularCourseExceptionsConfigurationController.java

private Collection<CompetenceCourse> parseCompetenceCoursesFromXLS(MultipartFile competenceCoursesFile)
        throws IOException {

    if (!competenceCoursesFile.getOriginalFilename().endsWith(".xls")) {
        throw new ULisboaSpecificationsDomainException(
                "error.curricularRules.manageAnyCurricularCourseExceptionsConfiguration.importCompetenceCourses.invalid.file.format");
    }//from  w  w  w . j ava2  s  .c  om

    final Set<CompetenceCourse> result = new HashSet<CompetenceCourse>();

    InputStream inputStream = null;
    HSSFWorkbook workbook = null;
    try {

        inputStream = competenceCoursesFile.getInputStream();
        workbook = new HSSFWorkbook(competenceCoursesFile.getInputStream());

        final HSSFSheet sheet = workbook.getSheetAt(0);
        final Iterator<Row> rowIterator = sheet.iterator();

        //header
        rowIterator.next();

        while (rowIterator.hasNext()) {

            final Row row = rowIterator.next();
            final String code = row.getCell(0).getStringCellValue();
            final CompetenceCourse competenceCourse = CompetenceCourse.find(code);

            if (competenceCourse == null) {
                throw new ULisboaSpecificationsDomainException(
                        "error.curricularRules.manageAnyCurricularCourseExceptionsConfiguration.importCompetenceCourses.competenceCourse.not.found",
                        code);
            }

            result.add(competenceCourse);

        }

        return result;

    } catch (IOException e) {
        throw new ULisboaSpecificationsDomainException("label.unexpected.error.occured");
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}