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.apache.openmeetings.servlet.outputhandler.UploadController.java

@RequestMapping(value = "/upload.upload", method = RequestMethod.POST)
public void handleFormUpload(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {/*from  w  w w  .  j a  va 2  s . c om*/
        UploadInfo info = validate(request, false);

        String room_id = request.getParameter("room_id");
        if (room_id == null) {
            room_id = "default";
        }
        String roomName = StringUtils.deleteWhitespace(room_id);

        String moduleName = request.getParameter("moduleName");
        if (moduleName == null) {
            moduleName = "nomodule";
        }
        if (moduleName.equals("nomodule")) {
            log.debug("module name missed");
            return;
        }
        boolean userProfile = moduleName.equals("userprofile");

        MultipartFile multipartFile = info.file;
        InputStream is = multipartFile.getInputStream();
        String fileSystemName = info.filename;
        fileSystemName = StringUtils.deleteWhitespace(fileSystemName);

        UploadCompleteMessage uploadCompleteMessage = new UploadCompleteMessage();
        uploadCompleteMessage.setUserId(info.userId);

        // Flash cannot read the response of an upload
        // httpServletResponse.getWriter().print(returnError);
        uploadFile(request, userProfile, info.userId, roomName, is, fileSystemName, uploadCompleteMessage);
        sendMessage(info, uploadCompleteMessage);
    } catch (ServletException e) {
        throw e;
    } catch (Exception e) {
        log.error("Exception during upload: ", e);
        throw new ServletException(e);
    }
}

From source file:org.apache.servicecomb.demo.springmvc.server.CodeFirstSpringmvc.java

private String _fileUpload(MultipartFile file1, Part file2) {
    try (InputStream is1 = file1.getInputStream(); InputStream is2 = file2.getInputStream()) {
        String content1 = IOUtils.toString(is1);
        String content2 = IOUtils.toString(is2);
        return String.format("%s:%s:%s\n" + "%s:%s:%s", file1.getOriginalFilename(), file1.getContentType(),
                content1, file2.getSubmittedFileName(), file2.getContentType(), content2);
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }//from  w  ww.ja va2  s.c  om
}

From source file:org.apache.servicecomb.demo.springmvc.server.CodeFirstSpringmvc.java

@PostMapping(path = "/upload1", produces = MediaType.TEXT_PLAIN_VALUE)
public String fileUpload1(@RequestPart(name = "file1") MultipartFile file1) throws IOException {
    try (InputStream is = file1.getInputStream()) {
        return IOUtils.toString(is);
    }/*ww w .  j av  a  2s  .  c om*/
}

From source file:org.apereo.portal.rest.ImportExportController.java

protected BufferedXMLEventReader createSourceXmlEventReader(MultipartFile multipartFile) throws IOException {
    final InputStream inputStream = multipartFile.getInputStream();
    final String name = multipartFile.getOriginalFilename();

    final XMLInputFactory xmlInputFactory = this.xmlUtilities.getXmlInputFactory();
    final XMLEventReader xmlEventReader;
    try {/*from   w w  w  . j  av  a 2 s  .  c om*/
        xmlEventReader = xmlInputFactory.createXMLEventReader(name, inputStream);
    } catch (XMLStreamException e) {
        throw new RuntimeException("Failed to create XML Event Reader for data Source", e);
    }
    return new BufferedXMLEventReader(xmlEventReader, -1);
}

From source file:org.broadleafcommerce.cms.admin.server.handler.StaticAssetCustomPersistenceHandler.java

@Override
public Entity add(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, RecordHelper helper)
        throws ServiceException {
    if (!persistencePackage.getEntity().isMultiPartAvailableOnThread()) {
        throw new ServiceException("Could not detect an uploaded file.");
    }/*  www  . j  a  va 2 s.  com*/
    MultipartFile upload = UploadedFile.getUpload().get("file");
    Entity entity = persistencePackage.getEntity();
    try {
        StaticAsset adminInstance;
        try {
            ImageMetadata metadata = imageArtifactProcessor.getImageMetadata(upload.getInputStream());
            adminInstance = new ImageStaticAssetImpl();
            ((ImageStaticAsset) adminInstance).setWidth(metadata.getWidth());
            ((ImageStaticAsset) adminInstance).setHeight(metadata.getHeight());
        } catch (Exception e) {
            //must not be an image stream
            adminInstance = new StaticAssetImpl();
        }
        Map<String, FieldMetadata> entityProperties = getMergedProperties();
        adminInstance = (StaticAsset) helper.createPopulatedInstance(adminInstance, entity, entityProperties,
                false);

        String fileName = getFileName(upload.getOriginalFilename());
        if (StringUtils.isEmpty(adminInstance.getName())) {
            adminInstance.setName(fileName);
        }
        if (StringUtils.isEmpty(adminInstance.getFullUrl())) {
            adminInstance.setFullUrl("/" + fileName);
        }

        adminInstance.setFileSize(upload.getSize());
        Collection mimeTypes = MimeUtil.getMimeTypes(upload.getOriginalFilename());
        if (!mimeTypes.isEmpty()) {
            MimeType mimeType = (MimeType) mimeTypes.iterator().next();
            adminInstance.setMimeType(mimeType.toString());
        } else {
            mimeTypes = MimeUtil.getMimeTypes(upload.getInputStream());
            if (!mimeTypes.isEmpty()) {
                MimeType mimeType = (MimeType) mimeTypes.iterator().next();
                adminInstance.setMimeType(mimeType.toString());
            }
        }
        String extension = upload.getOriginalFilename()
                .substring(upload.getOriginalFilename().lastIndexOf('.') + 1,
                        upload.getOriginalFilename().length())
                .toLowerCase();
        adminInstance.setFileExtension(extension);

        String fullUrl = adminInstance.getFullUrl();
        if (!fullUrl.startsWith("/")) {
            fullUrl = '/' + fullUrl;
        }
        if (fullUrl.lastIndexOf('.') < 0) {
            fullUrl += '.' + extension;
        }
        adminInstance.setFullUrl(fullUrl);

        adminInstance = staticAssetService.addStaticAsset(adminInstance, getSandBox());

        Entity adminEntity = helper.getRecord(entityProperties, adminInstance, null, null);

        StaticAssetStorage storage = staticAssetStorageService.create();
        storage.setStaticAssetId(adminInstance.getId());
        Blob uploadBlob = staticAssetStorageService.createBlob(upload);
        storage.setFileData(uploadBlob);
        staticAssetStorageService.save(storage);

        return addImageRecords(adminEntity);
    } catch (Exception e) {
        LOG.error("Unable to perform add for entity: " + entity.getType()[0], e);
        throw new ServiceException("Unable to add entity for " + entity.getType()[0], e);
    }
}

From source file:org.broadleafcommerce.cms.file.service.StaticAssetServiceImpl.java

@Override
@Transactional(TransactionUtils.DEFAULT_TRANSACTION_MANAGER)
public StaticAsset createStaticAssetFromFile(MultipartFile file, Map<String, String> properties) {
    try {//w  ww .  java  2  s  .co  m
        return createStaticAsset(file.getInputStream(), file.getOriginalFilename(), file.getSize(), properties);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.broadleafcommerce.cms.file.service.StaticAssetStorageServiceImpl.java

@Transactional("blTransactionManagerAssetStorageInfo")
@Override//from w w  w . ja va 2s . c  om
public void createStaticAssetStorageFromFile(MultipartFile file, StaticAsset staticAsset) throws IOException {
    createStaticAssetStorage(file.getInputStream(), staticAsset);
}

From source file:org.cloud.mblog.utils.FileUtil.java

/**
 * ?//from www .j  a v  a2 s. co m
 *
 * @param avatar_file
 * @param request
 * @param x
 * @param y
 * @param width
 * @param height
 * @return
 */
public static ResponseMessage processCropPost(MultipartFile avatar_file, HttpServletRequest request, float x,
        float y, float width, float height) {
    LocalDateTime now = LocalDateTime.now();
    String realFolder = LOCALROOT + getThumbRelativePathByDate(now);
    String urlPath = getThumbUrlPathByDate(now);
    // MIMEtype
    String type = avatar_file.getContentType();
    if (type == null || !type.toLowerCase().startsWith("image/")) {
        return new ResponseMessage("????", null);
    }

    String sourceFileName = avatar_file.getOriginalFilename();
    String fileType = sourceFileName.substring(sourceFileName.lastIndexOf(".") + 1);
    String fileName = getDateTypeFileName(now, fileType);
    String fullUrl = urlPath + "/" + fileName;

    // 
    File targetFile = new File(realFolder, fileName);
    // ?
    try {
        if (!targetFile.exists()) {
            InputStream is = avatar_file.getInputStream();
            ImageUtil.cutAndScale(ImageIO.read(is), targetFile, (int) x, (int) y, (int) width, (int) height,
                    500, 300);
            is.close();
        }
    } catch (Exception e) {
        logger.error("error", e);
        return new ResponseMessage("" + e.getMessage(), null);
    }
    return new ResponseMessage("?", fullUrl);
}

From source file:org.codelabor.system.file.web.controller.xplatform.FileController.java

@RequestMapping("/upload")
public String upload(Model model, FileList fileList) throws Exception {
    logger.debug("upload");

    List<MultipartFile> uploadedFileList = fileList.getFile();
    Iterator<MultipartFile> iter = uploadedFileList.iterator();

    logger.debug("uploadedFileList: {}", uploadedFileList);

    String mapId = fileList.getMapId();
    RepositoryType acceptedRepositoryType = repositoryType;
    String requestedRepositoryType = fileList.getRepositoryType();
    if (StringUtils.isNotEmpty(requestedRepositoryType)) {
        acceptedRepositoryType = RepositoryType.valueOf(requestedRepositoryType);
    }//from  ww w  .j av a  2  s.c o  m

    DataSetList outputDataSetList = new DataSetList();
    VariableList outputVariableList = new VariableList();

    try {
        while (iter.hasNext()) {
            MultipartFile uploadedFile = iter.next();

            String originalFilename = uploadedFile.getOriginalFilename();
            if (originalFilename == null || originalFilename.length() == 0)
                continue;

            // set DTO
            FileDTO fileDTO = new FileDTO();
            fileDTO.setMapId(mapId);
            fileDTO.setRealFilename(FilenameUtils.getName(originalFilename));
            if (acceptedRepositoryType == RepositoryType.FILE_SYSTEM) {
                logger.debug("uniqueFilenameGenerationService: {}", uniqueFilenameGenerationService);
                fileDTO.setUniqueFilename(uniqueFilenameGenerationService.getNextStringId());
            }
            fileDTO.setContentType(uploadedFile.getContentType());
            fileDTO.setRepositoryPath(repositoryPath);
            logger.debug(fileDTO.toString());

            UploadUtils.processFile(acceptedRepositoryType, uploadedFile.getInputStream(), fileDTO);

            if (fileDTO != null)
                fileManager.insertFile(fileDTO);
        }
        XplatformUtils.setSuccessMessage(
                messageSource.getMessage("info.success", new Object[] {}, forcedLocale), outputVariableList);
        logger.debug("success");
    } catch (Exception e) {
        logger.error("fail");
        e.printStackTrace();
        logger.error(e.getMessage());
        throw new XplatformException(messageSource.getMessage("error.failure", new Object[] {}, forcedLocale),
                e);
    }
    model.addAttribute(OUTPUT_DATA_SET_LIST, outputDataSetList);
    model.addAttribute(OUTPUT_VARIABLE_LIST, outputVariableList);
    return VIEW_NAME;
}

From source file:org.codelabor.system.file.web.spring.controller.FileController.java

@RequestMapping("upload")
public String upload(FileList fileList) throws Exception {
    String viewName = "redirect:/example/file/spring/mvc/list.do";

    List<MultipartFile> uploadedFileList = fileList.getFile();
    Iterator<MultipartFile> iter = uploadedFileList.iterator();

    String mapId = fileList.getMapId();
    RepositoryType acceptedRepositoryType = repositoryType;
    String requestedRepositoryType = fileList.getRepositoryType();
    if (StringUtils.isNotEmpty(requestedRepositoryType)) {
        acceptedRepositoryType = RepositoryType.valueOf(requestedRepositoryType);
    }//  www .ja va2  s .  c om

    while (iter.hasNext()) {
        MultipartFile uploadedFile = iter.next();

        String originalFilename = uploadedFile.getOriginalFilename();
        if (originalFilename == null || originalFilename.length() == 0)
            continue;

        // set DTO
        FileDTO fileDTO = new FileDTO();
        fileDTO.setMapId(mapId);
        fileDTO.setRealFilename(FilenameUtils.getName(originalFilename));
        if (acceptedRepositoryType == RepositoryType.FILE_SYSTEM) {
            logger.debug("uniqueFilenameGenerationService: {}", uniqueFilenameGenerationService);
            fileDTO.setUniqueFilename(uniqueFilenameGenerationService.getNextStringId());
        }
        fileDTO.setContentType(uploadedFile.getContentType());
        fileDTO.setRepositoryPath(repositoryPath);
        logger.debug(fileDTO.toString());

        UploadUtils.processFile(acceptedRepositoryType, uploadedFile.getInputStream(), fileDTO);

        if (fileDTO != null)
            fileManager.insertFile(fileDTO);
    }

    return viewName;
}