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:com.dlshouwen.tdjs.album.controller.TdjsAlbumController.java

/**
 * //from  w  ww.  jav  a 2s  .c o m
 *
 * @param album 
 * @param bindingResult 
 * @return ajax?
 * @throws Exception 
 */
@RequestMapping(value = "/edit", method = RequestMethod.POST)
public void editAlbum(@Valid Album album, HttpServletRequest request, BindingResult bindingResult,
        HttpServletResponse response) throws Exception {
    //      AJAX?
    AjaxResponse ajaxResponse = new AjaxResponse();
    //      ??
    if (bindingResult.hasErrors()) {
        ajaxResponse.bindingResultHandler(bindingResult);
        //           ?
        LogUtils.updateOperationLog(request, OperationType.UPDATE,
                "id" + album.getAlbum_id() + "??"
                        + album.getAlbum_name() + "?"
                        + AjaxResponse.getBindingResultMessage(bindingResult) + "");
        response.setContentType("text/html;charset=utf-8");
        JSONObject obj = JSONObject.fromObject(ajaxResponse);
        response.getWriter().write(obj.toString());
        return;
    }
    String path = "";
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("picture");
    String orgFileName = multipartFile.getOriginalFilename();
    if (multipartFile != null && StringUtils.isNotEmpty(orgFileName)) {
        JSONObject jobj = FileUploadClient.upFile(request, orgFileName, multipartFile.getInputStream());
        if (jobj != null && jobj.getString("responseMessage").equals("OK")) {
            path = jobj.getString("fpath");
        }
    }
    //      ??
    album.setAlbum_coverpath(path);
    //   ????
    Date nowDate = new Date();
    //      ?
    album.setAlbum_updatedate(nowDate);

    //      
    dao.updateAlbum(album);
    //      ????
    ajaxResponse.setSuccess(true);
    ajaxResponse.setSuccessMessage("??");
    //?
    Map map = new HashMap();
    map.put("URL", "tdjs/tdjsAlbum/album");
    ajaxResponse.setExtParam(map);

    //      ?
    LogUtils.updateOperationLog(request, OperationType.UPDATE,
            "id" + album.getAlbum_id() + "??" + album.getAlbum_name());
    response.setContentType("text/html;charset=utf-8");
    JSONObject obj = JSONObject.fromObject(ajaxResponse);
    response.getWriter().write(obj.toString());
}

From source file:org.sakaiproject.imagegallery.integration.sakai.FileLibraryLegacyResources.java

public ImageFile storeImageFile(MultipartFile sourceImageFile) {
    String filename = sourceImageFile.getOriginalFilename();
    String collectionId = getSiteCollectionId(galleryCollectionName);
    try {/*from   ww w  . j av  a  2  s . co  m*/
        ContentResourceEdit resource = contentHostingService.addResource(collectionId,
                FilenameUtils.getBaseName(filename), FilenameUtils.getExtension(filename), 500);
        resource.setContentType(sourceImageFile.getContentType());
        resource.setContent(sourceImageFile.getInputStream());
        contentHostingService.commitResource(resource);
        return mapResourceToImageFile(resource);
    } catch (PermissionException e) {
        throw new RuntimeException(e);
    } catch (IdUniquenessException e) {
        throw new RuntimeException(e);
    } catch (IdLengthException e) {
        throw new RuntimeException(e);
    } catch (IdInvalidException e) {
        throw new RuntimeException(e);
    } catch (IdUnusedException e) {
        throw new RuntimeException(e);
    } catch (OverQuotaException e) {
        throw new RuntimeException(e);
    } catch (ServerOverloadException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:controller.InternshipController.java

@RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST)
public String uploadMultipleFileHandler(@ModelAttribute("SpringWeb") docs.ApplicationModel application,
        ModelMap model, HttpSession session, @RequestParam("file") MultipartFile[] files) {

    if (session.getAttribute("userID") != null) {
        int idUser = (int) session.getAttribute("userID");
        STUDENTTYPE user = BusControl.getStudentbyId(idUser);

        application.setFirstName((String) user.getFIRSTNAME());
        application.setLastName((String) user.getLASTNAME());
        application.setMail((String) user.getMAIL());

        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            System.out.println("Taille : " + file.getSize());

            try {
                byte[] bytes = file.getBytes();
                file.getInputStream().read(bytes);
                System.out.println("URL retourne : " + BusControl.uploadCV(bytes));
                if (i == 0)
                    application.setCvPath(BusControl.uploadCV(bytes));
                if (i == 1)
                    application.setClPath(BusControl.uploadCV(bytes));
            } catch (Exception e) {
            }/*from  w ww.j a  v a 2s .  co m*/
        }

        //Ajouter une application  la BD Entreprise
        int applicationID = BusControl.addNewApplicant(application);

        //Ajouter une application  la BD
        BusControl.createApplication(idUser, 3, applicationID, 0);

        //mise  jour de la liste de candidature
        APPLICATIONTYPE listCand = getApplications(idUser);
        ArrayList<Applications> listCan = new ArrayList<>();

        if (listCand != null) {
            Iterator<APPLICATION> ite = listCand.getAPPLICATIONS().iterator();
            while (ite.hasNext()) {
                APPLICATION offer = ite.next();
                InternshipCompanyModel inte = BusControl
                        .getOffersById(BusControl.getAppById(offer.getApplicationID()).getInternshipID());
                int statusId = BusControl.getAppById(offer.getApplicationID()).getStatus();
                String status = Utils.getStatus(statusId);
                COMPANYTYPE com = BusControl.getCompanybyId(offer.getCompanyID());

                Applications can = new Applications(offer.getApplicationID(), null, inte, com.getNOM(),
                        com.getMAIL(), com.getADDRESS(), status);
                if (statusId != 4) {
                    listCan.add(can);
                }

            }
        } else {
            listCan = null;
        }
        model.addAttribute("listCan", listCan);

        Utils.drawHomePage(session.getAttribute("userName").toString(),
                BusControl.getNotifications(idUser).getNOTIFS().size(), "searchStudent", "candidatureStudent",
                model);
        return "home";
    } else {
        model.addAttribute("errormessage", " You need to be authenticated. ");
        return "connection";
    }
}

From source file:com.dlshouwen.tdjs.album.controller.TdjsAlbumController.java

/**
 * /* w w  w.j a  v a  2 s.c o m*/
 *
 * @param album 
 * @param bindingResult 
 * @param request 
 * @return ajax?
 * @throws Exception 
 */
@RequestMapping(value = "/add", method = RequestMethod.POST)
public void addAlbum(@Valid Album album, BindingResult bindingResult, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    AjaxResponse ajaxResponse = new AjaxResponse();

    if (bindingResult.hasErrors()) {
        ajaxResponse.bindingResultHandler(bindingResult);
        LogUtils.updateOperationLog(request, OperationType.INSERT,
                "??" + album.getAlbum_name() + "?"
                        + AjaxResponse.getBindingResultMessage(bindingResult) + "");
        response.setContentType("text/html;charset=utf-8");
        JSONObject obj = JSONObject.fromObject(ajaxResponse);
        response.getWriter().write(obj.toString());
        return;
    }
    String path = "";
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("picture");
    String orgFileName = multipartFile.getOriginalFilename();
    if (multipartFile != null && StringUtils.isNotEmpty(orgFileName)) {
        JSONObject jobj = FileUploadClient.upFile(request, orgFileName, multipartFile.getInputStream());
        if (jobj != null && jobj.getString("responseMessage").equals("OK")) {
            path = jobj.getString("fpath");
        }
    }
    //??
    album.setAlbum_coverpath(path);

    //      ????
    SessionUser sessionUser = (SessionUser) request.getSession().getAttribute(CONFIG.SESSION_USER);
    String userName = sessionUser.getUser_name();
    String userId = sessionUser.getUser_id();
    Date nowDate = new Date();
    //      ?????
    album.setAlbum_id(new GUID().toString());
    album.setAlbum_createuser(userName);
    album.setAlbum_createuserbyid(userId);
    album.setAlbum_createdate(nowDate);

    //      
    dao.insertAlbum(album);
    //      ????
    ajaxResponse.setSuccess(true);
    ajaxResponse.setSuccessMessage("??");

    //?
    Map map = new HashMap();
    map.put("URL", "tdjs/tdjsAlbum/album");
    ajaxResponse.setExtParam(map);

    //      ?
    LogUtils.updateOperationLog(request, OperationType.INSERT,
            "id" + album.getAlbum_id() + "??" + album.getAlbum_name());
    response.setContentType("text/html;charset=utf-8");
    JSONObject obj = JSONObject.fromObject(ajaxResponse);
    response.getWriter().write(obj.toString());
    return;
}

From source file:edu.mayo.qdm.webapp.rest.controller.TranslatorController.java

/**
 * Creates the exceuction./*from  w ww .  ja va  2s.c om*/
 *
 * @param request the request
 * @param startDate the start date
 * @param endDate the end date
 * @return the object
 * @throws Exception the exception
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@RequestMapping(value = "/executor/executions", method = RequestMethod.POST)
public synchronized Object createExceuction(HttpServletRequest request,
        final @RequestParam(required = true) String startDate,
        final @RequestParam(required = true) String endDate,
        final @RequestParam(required = false) String valueSetDefinitions) throws Exception {
    //For now, don't validate the date. This requirement may
    //come back at some point.
    //this.dateValidator.validateDate(startDate, DateType.START);
    //this.dateValidator.validateDate(endDate, DateType.END);

    if (!(request instanceof MultipartHttpServletRequest)) {
        throw new IllegalStateException("ServletRequest expected to be of type MultipartHttpServletRequest");
    }

    final Map<String, String> valueSetDefinitionsMap = valueSetDefinitions != null
            ? new ObjectMapper().readValue(valueSetDefinitions, HashMap.class)
            : Collections.EMPTY_MAP;

    final MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    final MultipartFile multipartFile = multipartRequest.getFile("file");

    final String id = this.idGenerator.getId();

    final FileSystemResult result = this.fileSystemResolver.getNewFiles(id);
    FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), result.getInputQdmXml());

    String xmlFileName = multipartFile.getOriginalFilename();

    final ExecutionInfo info = new ExecutionInfo();
    info.setId(id);
    info.setStatus(Status.PROCESSING);
    info.setStart(new Date());
    info.setParameters(new Parameters(startDate, endDate, xmlFileName));

    this.fileSystemResolver.setExecutionInfo(id, info);

    this.executorService.submit(new Runnable() {

        @Override
        public void run() {
            ExecutionResult translatorResult = null;
            try {

                translatorResult = launcher.launchTranslator(IOUtils.toString(multipartFile.getInputStream()),
                        dateValidator.parse(startDate), dateValidator.parse(endDate), valueSetDefinitionsMap);

                info.setStatus(Status.COMPLETE);
                info.setFinish(new Date());
                fileSystemResolver.setExecutionInfo(id, info);

                FileUtils.writeStringToFile(result.getOuptutResultXml(), translatorResult.getXml());
            } catch (Exception e) {
                info.setStatus(Status.FAILED);
                info.setFinish(new Date());

                info.setError(ExceptionUtils.getFullStackTrace(e));
                fileSystemResolver.setExecutionInfo(id, info);

                log.warn(e);
                throw new RuntimeException(e);
            }
        }

    });

    if (this.isHtmlRequest(multipartRequest)) {
        return new ModelAndView("redirect:/executor/executions");
    } else {
        String locationUrl = "executor/execution/" + id;

        final HttpHeaders headers = new HttpHeaders();
        headers.setLocation(URI.create(locationUrl));

        return new ResponseEntity(headers, HttpStatus.CREATED);
    }

}

From source file:com.denimgroup.threadfix.importer.loader.ScanTypeCalculationServiceImpl.java

private String saveFile(String inputFileName, MultipartFile file) {
    String returnValue = null;/*from w  w  w .  j a  v a 2 s .c  o m*/

    InputStream stream = null;
    FileOutputStream out = null;
    try {

        stream = file.getInputStream();
        File diskFile = DiskUtils.getScratchFile(inputFileName);
        try {
            out = new FileOutputStream(diskFile);
            byte[] buf = new byte[1024];
            int len;

            while ((len = stream.read(buf)) > 0) {
                out.write(buf, 0, len);
            }

            returnValue = inputFileName;

        } catch (IOException e) {
            log.warn("Writing the file stream to disk encountered an IOException.");
            throw new RestIOException(e, "Writing the file stream to disk encountered an IOException. "
                    + e.getMessage() + ". Check your File Upload Location setting.");
        }
    } catch (IOException e) {
        log.warn("Failed to retrieve an InputStream from the file upload.");
        throw new RestIOException(e, "Failed to retrieve an InputStream from the file upload. " + e.getMessage()
                + ". Check your File Upload Location setting.");
    } finally {
        closeQuietly(stream);
        closeQuietly(out);
    }

    return returnValue;
}

From source file:cherry.foundation.async.AsyncFileProcessHandlerImplTest.java

@Test
public void testLaunchFileProcess_IOException() throws Exception {

    AsyncFileProcessHandlerImpl impl = createImpl();

    LocalDateTime now = LocalDateTime.now();
    when(bizDateTime.now()).thenReturn(now);
    when(asyncProcessStore.createFileProcess("a", now, "b", "c", "d", "e", 100L, "f")).thenReturn(10L);

    IOException ioException = new IOException();
    MultipartFile file = mock(MultipartFile.class);
    when(file.getName()).thenReturn("c");
    when(file.getOriginalFilename()).thenReturn("d");
    when(file.getContentType()).thenReturn("e");
    when(file.getSize()).thenReturn(100L);
    when(file.getInputStream()).thenThrow(ioException);

    try {/*from www  .j av a2  s. c o  m*/
        impl.launchFileProcess("a", "b", file, "f");
        fail("Exception must be thrown");
    } catch (IllegalStateException ex) {
        assertEquals(ioException, ex.getCause());
    }
}

From source file:eu.freme.eservices.publishing.ServiceRestController.java

@RequestMapping(value = "/e-publishing/html", method = RequestMethod.POST)
public ResponseEntity<byte[]> htmlToEPub(@RequestParam("htmlZip") MultipartFile file,
        @RequestParam("metadata") String jMetadata)
        throws IOException, InvalidZipException, EPubCreationException, MissingMetadataException {
    Gson gson = new Gson();
    Metadata metadata = gson.fromJson(jMetadata, Metadata.class);
    MultiValueMap<String, String> headers = new HttpHeaders();
    headers.add(HttpHeaders.CONTENT_TYPE, "Application/epub+zip");
    String filename = file.getName();
    headers.add(HttpHeaders.CONTENT_DISPOSITION, "Attachment; filename=" + filename.split("\\.")[0] + ".epub");
    try (InputStream in = file.getInputStream()) {
        return new ResponseEntity<>(epubAPI.createEPUB(metadata, in), headers, HttpStatus.OK);
    }//w ww .  ja v  a2 s.co m
}

From source file:cherry.foundation.async.AsyncFileProcessHandlerImplTest.java

@Test
public void testLaunchFileProcess_exception() throws Exception {

    AsyncFileProcessHandlerImpl impl = createImpl();

    LocalDateTime now = LocalDateTime.now();
    when(bizDateTime.now()).thenReturn(now);
    when(asyncProcessStore.createFileProcess("a", now, "b", "c", "d", "e", 100L, "f")).thenReturn(10L);

    IOException exception = new IOException();
    InputStream in = mock(InputStream.class);
    when(in.read((byte[]) any())).thenThrow(exception);

    MultipartFile file = mock(MultipartFile.class);
    when(file.getName()).thenReturn("c");
    when(file.getOriginalFilename()).thenReturn("d");
    when(file.getContentType()).thenReturn("e");
    when(file.getSize()).thenReturn(100L);
    when(file.getInputStream()).thenReturn(in);

    try {/*from  w w  w  . ja v a2s .co m*/
        impl.launchFileProcess("a", "b", file, "f");
        fail("Exception must be thrown");
    } catch (IllegalStateException ex) {
        verify(asyncProcessStore).createFileProcess("a", now, "b", "c", "d", "e", 100L, "f");
        verify(asyncProcessStore).finishWithException(10L, now, exception);
    }
}

From source file:cherry.foundation.async.AsyncFileProcessHandlerImplTest.java

@Test
public void testLaunchFileProcess_NO_ARG() throws Exception {

    AsyncFileProcessHandlerImpl impl = createImpl();

    LocalDateTime now = LocalDateTime.now();
    when(bizDateTime.now()).thenReturn(now);
    when(asyncProcessStore.createFileProcess("a", now, "b", "c", "d", "e", 100L, "f")).thenReturn(10L);

    MultipartFile file = mock(MultipartFile.class);
    when(file.getName()).thenReturn("c");
    when(file.getOriginalFilename()).thenReturn("d");
    when(file.getContentType()).thenReturn("e");
    when(file.getSize()).thenReturn(100L);
    when(file.getInputStream()).thenReturn(new ByteArrayInputStream(new byte[0]));

    @SuppressWarnings("rawtypes")
    ArgumentCaptor<Map> message = ArgumentCaptor.forClass(Map.class);

    long asyncId = impl.launchFileProcess("a", "b", file, "f");
    assertEquals(10L, asyncId);/*from www .j  ava2  s . co m*/
    verify(jmsOperations).convertAndSend(message.capture(), eq(messagePostProcessor));
    assertEquals("10", message.getValue().get("asyncId"));
    String fileName = (String) message.getValue().get("file");
    assertTrue(fileName.startsWith((new File(tempDir, "prefix_")).getAbsolutePath()));
    assertTrue(fileName.endsWith(".csv"));
    assertEquals("c", message.getValue().get("name"));
    assertEquals("d", message.getValue().get("originalFilename"));
    assertEquals("e", message.getValue().get("contentType"));
    assertEquals("100", message.getValue().get("size"));
    assertEquals("f", message.getValue().get("handlerName"));
    verify(asyncProcessStore).createFileProcess("a", now, "b", "c", "d", "e", 100L, "f");
    verify(asyncProcessStore).updateToLaunched(10L, now);
}