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:cherry.foundation.async.AsyncFileProcessHandlerImplTest.java

@Test
public void testLaunchFileProcess_2_ARGS() 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", "g", "h"))
            .thenReturn(10L);/* ww  w  .  j a  v  a  2 s  .  com*/

    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", "g", "h");
    assertEquals(10L, asyncId);
    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"));
    assertEquals("g", message.getValue().get("0"));
    assertEquals("h", message.getValue().get("1"));
    verify(asyncProcessStore).createFileProcess("a", now, "b", "c", "d", "e", 100L, "f", "g", "h");
    verify(asyncProcessStore).updateToLaunched(10L, now);
}

From source file:fr.xebia.cocktail.CocktailManager.java

/**
 * TODO use PUT instead of POST//from   w w  w.j a  v a2 s  .  c om
 *
 * @param id    id of the cocktail
 * @param photo to associate with the cocktail
 * @return redirection to display cocktail
 */
@RequestMapping(value = "/cocktail/{id}/photo", method = RequestMethod.POST)
public String updatePhoto(@PathVariable String id, @RequestParam("photo") MultipartFile photo) {

    if (!photo.isEmpty()) {
        try {
            String contentType = fileStorageService.findContentType(photo.getOriginalFilename());
            if (contentType == null) {
                logger.warn("photo",
                        "Skip file with unsupported extension '" + photo.getOriginalFilename() + "'");
            } else {

                InputStream photoInputStream = photo.getInputStream();
                long photoSize = photo.getSize();

                Map metadata = new TreeMap();
                metadata.put("Content-Length", Arrays.asList(new String[] { "" + photoSize }));
                metadata.put("Content-Type", Arrays.asList(new String[] { contentType }));
                metadata.put("Cache-Control", Arrays.asList(
                        new String[] { "public, max-age=" + TimeUnit.SECONDS.convert(365, TimeUnit.DAYS) }));

                /*    ObjectMetadata objectMetadata = new ObjectMetadata();
                    objectMetadata.setContentLength(photoSize);
                    objectMetadata.setContentType(contentType);
                    objectMetadata.setCacheControl("public, max-age=" + TimeUnit.SECONDS.convert(365, TimeUnit.DAYS));*/
                String photoUrl = fileStorageService.storeFile(photo.getBytes(), metadata);

                Cocktail cocktail = cocktailRepository.get(id);
                logger.info("Saved {}", photoUrl);
                cocktail.setPhotoUrl(photoUrl);
                cocktailRepository.update(cocktail);
            }

        } catch (IOException e) {
            throw Throwables.propagate(e);
        }
    }
    return "redirect:/cocktail/" + id;
}

From source file:com.ogaclejapan.dotapk.manager.ApkFileManager.java

@Override
public void save(MultipartFile file) throws WebApiException {
    if (!file.getOriginalFilename().endsWith(".apk")) {
        throw WebApiException.asBadRequest("file must be format *.apk: ");
    }// w w w  . j av  a 2s.c  o m

    log.debug("save apk: {}", file.getOriginalFilename());

    File apkfile = new File(apkDir, file.getOriginalFilename());
    if (apkfile.exists()) {
        if (!FileUtils.deleteQuietly(apkfile)) {
            throw WebApiException.asInternalServerError("can not delete old apk.");
        }
    }

    try {
        FileUtils.copyInputStreamToFile(file.getInputStream(), apkfile);
    } catch (IOException ioe) {
        throw WebApiException.asInternalServerError("can not save apk.", ioe);
    }
}

From source file:org.iti.agrimarket.view.FileUploadController.java

public String handleFileUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file,
        RedirectAttributes redirectAttributes) {
    if (name.contains("/")) {
        redirectAttributes.addFlashAttribute("message", "Folder separators not allowed");
        return "redirect:/";
    }/*from  w  w w .j  ava 2  s. co m*/
    if (name.contains("/")) {
        redirectAttributes.addFlashAttribute("message", "Relative pathnames not allowed");
        return "redirect:/";
    }

    if (!file.isEmpty()) {
        try {
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(name)));
            FileCopyUtils.copy(file.getInputStream(), stream);
            stream.close();
            redirectAttributes.addFlashAttribute("message", "You successfully uploaded " + name + "!");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("message",
                    "You failed to upload " + name + " => " + e.getMessage());
        }
    } else {
        redirectAttributes.addFlashAttribute("message",
                "You failed to upload " + name + " because the file was empty");
    }

    return "redirect:/index";
}

From source file:com.cloudbees.demo.beesshop.web.ProductController.java

/**
 * @param id    id of the product//from   w  w w  .j  a  v  a 2  s .  c  o  m
 * @param photo to associate with the product
 * @return redirection to display product
 */
@RequestMapping(value = "/product/{id}/photo", method = RequestMethod.POST)
@Transactional
public String updatePhoto(@PathVariable long id, @RequestParam("photo") MultipartFile photo) {

    if (photo.getSize() == 0) {
        logger.info("Empty uploaded file");
    } else {
        try {
            String contentType = fileStorageService.findContentType(photo.getOriginalFilename());
            if (contentType == null) {
                logger.warn("Skip file with unsupported extension '{}'", photo.getName());
            } else {

                InputStream photoInputStream = photo.getInputStream();
                long photoSize = photo.getSize();

                ObjectMetadata objectMetadata = new ObjectMetadata();
                objectMetadata.setContentLength(photoSize);
                objectMetadata.setContentType(contentType);
                objectMetadata
                        .setCacheControl("public, max-age=" + TimeUnit.SECONDS.convert(365, TimeUnit.DAYS));
                String photoUrl = fileStorageService.storeFile(photoInputStream, objectMetadata);

                Product product = productRepository.get(id);
                logger.info("Saved {}", photoUrl);
                product.setPhotoUrl(photoUrl);
                productRepository.update(product);
            }

        } catch (IOException e) {
            throw Throwables.propagate(e);
        }
    }
    return "redirect:/product/" + id;
}

From source file:gateway.controller.util.GatewayUtil.java

/**
 * Handles the uploaded file from the data/file endpoint. This will push the file to S3, and then modify the content
 * of the job to reference the new S3 location of the file.
 * // www .  j  av a 2s . c  o  m
 * @param jobId
 *            The Id of the Job, used for generating a unique S3 bucket file name.
 * @param job
 *            The ingest job, containing the DataResource metadata
 * @param file
 *            The file to be uploaded
 * @return The modified job, with the location of the S3 file added to the metadata
 */
public IngestJob pushS3File(String jobId, IngestJob job, MultipartFile file)
        throws AmazonServiceException, AmazonClientException, IOException {
    // The content length must be specified.
    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentLength(file.getSize());
    // Send the file to S3. The key corresponds with the S3 file name.
    String fileKey = String.format("%s-%s", jobId, file.getOriginalFilename());
    s3Client.putObject(AMAZONS3_BUCKET_NAME, fileKey, file.getInputStream(), metadata);
    // Note the S3 file path in the Ingest Job.
    // Attach the file to the FileLocation object
    FileLocation fileLocation = new S3FileStore(AMAZONS3_BUCKET_NAME, fileKey, file.getSize(), AMAZONS3_DOMAIN);
    ((FileRepresentation) job.getData().getDataType()).setLocation(fileLocation);
    logger.log(String.format("S3 File for Job %s Persisted to %s:%s", jobId, AMAZONS3_BUCKET_NAME, fileKey),
            PiazzaLogger.INFO);
    return job;
}

From source file:edu.dfci.cccb.mev.controllers.HeatmapController.java

@RequestMapping(value = "/{id}/annotation/{dimension}", method = { POST, PUT })
@ResponseStatus(OK)//from   w  w  w  .ja va 2  s  .  c  o  m
public void annotate(@PathVariable("id") String id, @PathVariable("dimension") String dimension,
        @RequestParam("filedata") MultipartFile data)
        throws HeatmapNotFoundException, InvalidDimensionException, IOException {
    if (isRow(dimension))
        get(id).setRowAnnotations(data.getInputStream());
    else if (isColumn(dimension))
        get(id).setColumnAnnotations(data.getInputStream());
    else
        throw new InvalidDimensionException(dimension);
}

From source file:it.cilea.osd.jdyna.controller.AFormEditTabController.java

/**
 * //from  www .j  a  v a 2s .  c om
 * Load tab icon and copy to default directory.
 * 
 * @param researcher
 * @param rp
 * @param itemImage
 *            MultipartFile to use in webform
 * @throws IOException
 * @throws FileNotFoundException
 */
public void loadTabIcon(ET tab, String iconName, MultipartFile itemImage)
        throws IOException, FileNotFoundException {
    String pathImage = tab.getFileSystemPath();
    String ext = itemImage.getOriginalFilename()
            .substring(itemImage.getOriginalFilename().lastIndexOf(".") + 1);
    File dir = new File(pathImage + File.separatorChar + DIRECTORY_TAB_ICON);
    dir.mkdir();
    File file = new File(dir, PREFIX_TAB_ICON + iconName + "." + ext);
    file.createNewFile();
    FileOutputStream out = new FileOutputStream(file);
    it.cilea.osd.common.util.Utils.bufferedCopy(itemImage.getInputStream(), out);
    out.close();
    tab.setExt(ext);
    tab.setMime(itemImage.getContentType());
}

From source file:it.cilea.osd.jdyna.controller.AFormTabController.java

/**
 * /*from w  w  w  . j a va2 s  . c o  m*/
 * Load tab icon and copy to default directory.
 * 
 * @param researcher
 * @param rp
 * @param itemImage
 *            MultipartFile to use in webform
 * @throws IOException
 * @throws FileNotFoundException
 */
public void loadTabIcon(T tab, String iconName, MultipartFile itemImage)
        throws IOException, FileNotFoundException {
    String pathImage = tab.getFileSystemPath();
    String ext = itemImage.getOriginalFilename()
            .substring(itemImage.getOriginalFilename().lastIndexOf(".") + 1);
    File dir = new File(pathImage + File.separatorChar + DIRECTORY_TAB_ICON);
    dir.mkdir();
    File file = new File(dir, PREFIX_TAB_ICON + iconName + "." + ext);
    file.createNewFile();
    FileOutputStream out = new FileOutputStream(file);
    it.cilea.osd.common.util.Utils.bufferedCopy(itemImage.getInputStream(), out);
    out.close();
    tab.setExt(ext);
    tab.setMime(itemImage.getContentType());
}

From source file:com.qcadoo.report.internal.controller.ReportDevelopmentController.java

@RequestMapping(value = "developReport/report", method = RequestMethod.POST)
public ModelAndView uploadReportFile(@RequestParam("file") final MultipartFile file,
        final HttpServletRequest request) {
    if (!showReportDevelopment) {
        return new ModelAndView(new RedirectView("/"));
    }// w  w w  .  j a v  a  2  s.  c o  m

    if (file.isEmpty()) {
        return new ModelAndView(L_QCADOO_REPORT_REPORT).addObject("isFileInvalid", true);
    }

    try {
        String template = IOUtils.toString(file.getInputStream());

        List<ReportParameter> params = getReportParameters(template);

        return new ModelAndView(L_QCADOO_REPORT_REPORT).addObject(L_TEMPLATE, template)
                .addObject("isParameter", true).addObject(L_PARAMS, params).addObject(L_LOCALE, "en");
    } catch (Exception e) {
        return showException(L_QCADOO_REPORT_REPORT, e);
    }
}