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.magnum.dataup.controller.VideoSvc.java

/**
 * Save stream video to disk//from  ww  w . j  a  v  a  2s  .  c o m
 * 
 * @param id
 *            Video identifier
 * @param data
 *            Stream that contains the video data
 * @return Object representing video status operation
 */
@RequestMapping(value = VideoSvcApi.VIDEO_DATA_PATH, method = RequestMethod.POST)
public @ResponseBody VideoStatus setVideoData(@PathVariable(VideoSvcApi.ID_PARAMETER) Long id,
        @RequestParam(VideoSvcApi.DATA_PARAMETER) MultipartFile data, HttpServletResponse response) {
    VideoStatus status = new VideoStatus(VideoState.PROCESSING);
    VideoFileManager fileMgm;
    try {
        if (repository.exists(id)) {
            fileMgm = VideoFileManager.get();
            Video video = repository.findOne(id);
            fileMgm.saveVideoData(video, data.getInputStream());
            status.setState(VideoState.READY);
        } else {
            response.setStatus(404);
        }
    } catch (IOException e) {
        response.setStatus(404);
    }
    return status;
}

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

@RequestMapping(method = RequestMethod.POST, produces = "text/html; charset=UTF-8")
public String updateTemplate(@RequestParam("name") String name, @RequestParam("language") String language,
        @RequestParam("file") MultipartFile file) {

    if (file.isEmpty()) {
        throw new WteFileUploadException(MessageKey.UPLOADED_FILE_NOT_READABLE);
    }/*from  w w  w . j a  v a  2 s .  c  o m*/

    Template<?> template = templateRepository.getTemplate(name, language);
    if (template == null) {
        throw new WteFileUploadException(MessageKey.TEMPLATE_NOT_FOUND);
    }

    try (InputStream in = file.getInputStream()) {
        template.update(in, serviceContext.getUser());
        templateRepository.persist(template);
        return fileUploadResponseFactory.createJsonSuccessResponse(MessageKey.TEMPLATE_UPLOADED);
    } catch (IOException e) {
        throw new WteFileUploadException(MessageKey.UPLOADED_FILE_NOT_READABLE);
    }
}

From source file:com.haulmont.restapi.controllers.FileUploadController.java

/**
 * Method for multipart file upload. It expects the file contents to be passed in the part called 'file'
 *//*w  w  w .j  a va  2  s. c  o m*/
@PostMapping(consumes = "multipart/form-data")
public ResponseEntity<FileInfo> uploadFile(@RequestParam("file") MultipartFile file,
        @RequestParam(required = false) String name, HttpServletRequest request) {
    try {
        if (Strings.isNullOrEmpty(name)) {
            name = file.getOriginalFilename();
        }

        long size = file.getSize();
        FileDescriptor fd = createFileDescriptor(name, size);

        InputStream is = file.getInputStream();
        uploadToMiddleware(is, fd);
        saveFileDescriptor(fd);

        return createFileInfoResponseEntity(request, fd);
    } catch (Exception e) {
        log.error("File upload failed", e);
        throw new RestAPIException("File upload failed", "File upload failed",
                HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.dataone.proto.trove.mn.rest.v1.ErrorController.java

@RequestMapping(value = { "/v1/error/", "/v1/error" }, method = RequestMethod.POST)
public void fail(MultipartHttpServletRequest fileRequest, HttpServletResponse response)
        throws InvalidSystemMetadata, InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique,
        UnsupportedType, InsufficientResources, NotImplemented, InvalidRequest {

    Session session = new Session();

    MultipartFile messageMultipart = null;
    SynchronizationFailed message;/*from   www  .ja  v a 2s. c  om*/
    Set<String> keys = fileRequest.getFileMap().keySet();
    for (String key : keys) {
        if (key.equalsIgnoreCase("message")) {
            messageMultipart = fileRequest.getFileMap().get(key);
        }
    }
    if (messageMultipart != null) {
        try {
            message = (SynchronizationFailed) ExceptionHandler.deserializeXml(messageMultipart.getInputStream(),
                    "something broke");
        } catch (IOException ex) {
            throw new InvalidSystemMetadata("15001", ex.getMessage());
        } catch (SAXException ex) {
            throw new InvalidSystemMetadata("15001", ex.getMessage());
        } catch (ParserConfigurationException ex) {
            throw new InvalidSystemMetadata("15001", ex.getMessage());
        }
    } else {
        throw new InvalidSystemMetadata("15005",
                "System Metadata was not found as Part of Multipart Mime message");
    }

    mnRead.synchronizationFailed(session, message);

}

From source file:org.hsweb.web.controller.file.FileController.java

/**
 * ,?.???,{@link FileService#saveFile(InputStream, String)}?
 * ??,??:[{"id":"fileId","name":"fileName","md5":"md5"}]
 *
 * @param files //  w  w  w .  j av  a 2  s  .  c  o  m
 * @return .
 * @throws IOException ?
 */
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@AccessLogger("")
public ResponseMessage upload(@RequestParam("file") MultipartFile[] files) throws IOException {
    if (logger.isInfoEnabled())
        logger.info(String.format("start upload , file number:%s", files.length));
    List<Resources> resourcesList = new LinkedList<>();
    for (int i = 0; i < files.length; i++) {
        MultipartFile file = files[i];
        if (!file.isEmpty()) {
            if (logger.isInfoEnabled())
                logger.info("start write file:{}", file.getOriginalFilename());
            String fileName = file.getOriginalFilename();
            Resources resources = fileService.saveFile(file.getInputStream(), fileName);
            resourcesList.add(resources);
        }
    } //????
    return ResponseMessage.ok(resourcesList).include(Resources.class, "id", "name", "md5");
}

From source file:org.openlmis.fulfillment.service.TemplateServiceTest.java

@Test
public void shouldThrowErrorIfThereAreExtraParameterProperties() throws Exception {
    expectedException.expect(ReportingException.class);
    expectedException.expectMessage(REPORTING_EXTRA_PROPERTIES);
    MultipartFile file = mock(MultipartFile.class);
    when(file.getOriginalFilename()).thenReturn(NAME_OF_FILE);

    mockStatic(JasperCompileManager.class);
    JasperReport report = mock(JasperReport.class);
    InputStream inputStream = mock(InputStream.class);
    when(file.getInputStream()).thenReturn(inputStream);

    JRParameter param1 = mock(JRParameter.class);
    JRPropertiesMap propertiesMap = mock(JRPropertiesMap.class);

    when(report.getParameters()).thenReturn(new JRParameter[] { param1 });
    when(JasperCompileManager.compileReport(inputStream)).thenReturn(report);
    when(param1.getPropertiesMap()).thenReturn(propertiesMap);
    String[] propertyNames = { "name1", "name2", "name3" };
    when(propertiesMap.getPropertyNames()).thenReturn(propertyNames);
    Template template = new Template();

    templateService.validateFileAndInsertTemplate(template, file);

    verify(templateService, never()).saveWithParameters(template);
}

From source file:com.healthcit.cacure.web.controller.ModuleImportExportController.java

@RequestMapping(method = RequestMethod.POST)
public ModelAndView importModule(@RequestParam("file") MultipartFile file, HttpServletRequest request,
        HttpServletResponse response) {/*ww w  .j  a  v  a  2  s.  com*/
    try {
        if (file != null) {
            Map<String, String> existingForms = new HashMap<String, String>();
            Map<String, String> existingModules = new HashMap<String, String>();
            List<String> existingQuestions = new ArrayList<String>();

            InputStream is = file.getInputStream();
            JAXBContext jc = JAXBContext.newInstance("com.healthcit.cacure.export.model");
            Unmarshaller m = jc.createUnmarshaller();
            Cure cure = (Cure) m.unmarshal(is);
            dataImporter.importModule(cure, existingModules, existingForms, existingQuestions);
            if (existingModules.size() > 0 || existingForms.size() > 0 || existingQuestions.size() > 0) {
                ModelAndView mav = new ModelAndView("formUploadStatus"); // initialize with view name
                ModelMap model = mav.getModelMap();
                model.addAttribute("existingModules", existingModules);
                model.addAttribute("existingForms", existingForms);
                model.addAttribute("existingQuestions", existingQuestions);
                return mav;
                /* there had been errors */
                //               return new ModelAndView("formUploadStatus", "existingForms", existingForms);
            }
        }
        return new ModelAndView("formUploadStatus", "status", "OK");

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return new ModelAndView("formUploadStatus", "status", "FAIL");
    }

}

From source file:org.openlmis.fulfillment.service.TemplateServiceTest.java

@Test
public void shouldThrowErrorIfDisplayNameOfParameterIsMissing() throws Exception {
    expectedException.expect(ReportingException.class);
    expectedException.expect(hasProperty("params", arrayContaining("displayName")));
    expectedException.expectMessage(REPORTING_PARAMETER_MISSING);

    MultipartFile file = mock(MultipartFile.class);
    when(file.getOriginalFilename()).thenReturn(NAME_OF_FILE);

    mockStatic(JasperCompileManager.class);
    JasperReport report = mock(JasperReport.class);
    InputStream inputStream = mock(InputStream.class);
    when(file.getInputStream()).thenReturn(inputStream);

    JRParameter param1 = mock(JRParameter.class);
    JRParameter param2 = mock(JRParameter.class);
    JRPropertiesMap propertiesMap = mock(JRPropertiesMap.class);

    when(report.getParameters()).thenReturn(new JRParameter[] { param1, param2 });
    when(JasperCompileManager.compileReport(inputStream)).thenReturn(report);
    when(param1.getPropertiesMap()).thenReturn(propertiesMap);
    String[] propertyNames = { "name1" };
    when(propertiesMap.getPropertyNames()).thenReturn(propertyNames);
    when(propertiesMap.getProperty(DISPLAY_NAME)).thenReturn(null);
    Template template = new Template();

    templateService.validateFileAndInsertTemplate(template, file);

    verify(templateService, never()).saveWithParameters(template);
}

From source file:aiai.ai.launchpad.resource.ResourceController.java

@PostMapping(value = "/resource-upload-from-file")
public String createResourceFromFile(MultipartFile file, @RequestParam(name = "code") String resourceCode,
        @RequestParam(name = "poolCode") String resourcePoolCode, final RedirectAttributes redirectAttributes) {
    File tempFile = globals.createTempFileForLaunchpad("temp-raw-file-");
    if (tempFile.exists()) {
        tempFile.delete();//w w w .j av  a  2  s.c  om
    }
    try {
        FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);
    } catch (IOException e) {
        redirectAttributes.addFlashAttribute("errorMessage", "#173.06 can't persist uploaded file as "
                + tempFile.getAbsolutePath() + ", error: " + e.toString());
        return "redirect:/launchpad/resources";
    }

    String originFilename = file.getOriginalFilename();
    if (originFilename == null) {
        redirectAttributes.addFlashAttribute("errorMessage", "#172.01 name of uploaded file is null");
        return "redirect:/launchpad/resources";
    }
    String code = StringUtils.isNotBlank(resourceCode) ? resourceCode : resourcePoolCode + '-' + originFilename;

    try {
        resourceService.storeInitialResource(originFilename, tempFile, code, resourcePoolCode, true,
                originFilename);
    } catch (StoreNewPartOfRawFileException e) {
        log.error("Error", e);
        redirectAttributes.addFlashAttribute("errorMessage",
                "#172.04 An error while saving data to file, " + e.toString());
        return "redirect:/launchpad/resources";
    }
    return "redirect:/launchpad/resources";
}

From source file:com.glaf.activiti.web.springmvc.ActivitiDeployController.java

/**
 * /*from   w  ww. j a va 2s .  c  om*/
 * @param model
 * @param mFile
 * @return
 * @throws IOException
 */
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(Model model, @RequestParam("file") MultipartFile mFile) throws IOException {
    if (!mFile.isEmpty()) {
        String deploymentId = null;
        ProcessDefinition processDefinition = null;
        if (mFile.getOriginalFilename().endsWith(".zip") || mFile.getOriginalFilename().endsWith(".jar")) {
            ZipInputStream zipInputStream = null;
            try {
                zipInputStream = new ZipInputStream(mFile.getInputStream());
                deploymentId = activitiDeployService.addZipInputStream(zipInputStream).getId();
            } finally {
                IOUtils.closeStream(zipInputStream);
            }
        } else {
            String resourceName = FileUtils.getFilename(mFile.getOriginalFilename());
            deploymentId = activitiDeployService.addInputStream(resourceName, mFile.getInputStream()).getId();
        }
        if (StringUtils.isNotEmpty(deploymentId)) {
            logger.debug("deploymentId:" + deploymentId);
            processDefinition = activitiProcessQueryService.getProcessDefinitionByDeploymentId(deploymentId);
            if (processDefinition != null) {
                model.addAttribute("processDefinition", processDefinition);
                model.addAttribute("deploymentId", processDefinition.getDeploymentId());
                String resourceName = processDefinition.getDiagramResourceName();
                if (resourceName != null) {
                    ProcessUtils.saveProcessImageToFileSystem(processDefinition);
                    String path = "/deploy/bpmn/" + ProcessUtils.getImagePath(processDefinition);
                    model.addAttribute("path", path);
                    return "/activiti/deploy/showImage";
                }
            }
        }
    }

    String view = ViewProperties.getString("activiti.deploy");
    if (StringUtils.isNotEmpty(view)) {
        return view;
    }

    return "/activiti/deploy/deploy";
}