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:de.tobiasbruns.content.storage.ContentController.java

private Content<InputStream> buildContent(MultipartFile file) {
    try {/*from  w  w  w .j ava  2s  . c  o  m*/
        Content<InputStream> content = new Content<>();
        content.setContent(file.getInputStream());
        content.getHeader().setContentType(file.getContentType());
        content.getHeader().setName(file.getOriginalFilename());
        return content;
    } catch (IOException e) {
        throw new RuntimeException("Error reading incoming file", e);
    }
}

From source file:it.cilea.osd.jdyna.editor.FilePropertyEditor.java

@Override
public void setValue(Object value) {
    if (value instanceof MultipartFile) {
        MultipartFile multipart = (MultipartFile) value;
        if (multipart.getSize() > 0) {
            try {
                EmbeddedFile file = widgetFile.load(multipart.getInputStream(), multipart.getOriginalFilename(),
                        multipart.getContentType(), getExternalAuthority(), getInternalAuthority());
                super.setValue(new ValoreDTO(file));
            } catch (IOException ex) {
                log.warn("Cannot read contents of multipart file", ex);
                throw new IllegalArgumentException(
                        "Cannot read contents of multipart file: " + ex.getMessage());

            }//from  w w w  .java 2 s  . c om
        } else {
            setValue(null);
        }
    } else {
        super.setValue(value);
    }
}

From source file:software.uncharted.rest.ImageSearchResource.java

@RequestMapping(value = "/file", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ImageSearchResult searchByFile(@RequestParam("image") final MultipartFile file) throws IOException {
    long start = System.nanoTime();
    String fileType = file.getContentType();
    if (fileType.startsWith("image")) {
        BufferedImage image = ImageIO.read(file.getInputStream());
        Set<Image> images = service.search(image);
        long duration = (System.nanoTime() - start) / 1000000L;
        return new ImageSearchResult().setImages(images).setDuration(duration);

    }//from   w w  w. ja  va2  s. c  o  m
    return ImageSearchResult.empty();
}

From source file:org.openmrs.module.dataexchange.web.controller.DataExchangeController.java

@RequestMapping(value = "/exportPackageContent", method = RequestMethod.POST)
public ResponseEntity<String> exportPackageContent(@RequestParam("file") MultipartFile file)
        throws IOException, ParserConfigurationException, SAXException {
    Set<Integer> conceptIds = metadataSharingParser.parseConceptIds(file.getInputStream());

    return exportConcepts(conceptIds);
}

From source file:org.openxdata.server.servlet.FormOpenServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from ww w  .j  av a 2s .c  o m*/
        CommonsMultipartResolver multipartResover = new CommonsMultipartResolver(/*this.getServletContext()*/);
        if (multipartResover.isMultipart(request)) {
            MultipartHttpServletRequest multipartRequest = multipartResover.resolveMultipart(request);
            MultipartFile uploadedFile = multipartRequest.getFile("filecontents");
            if (uploadedFile != null && !uploadedFile.isEmpty())
                request.getSession().setAttribute(KEY_FILE_CONTENTS,
                        IOUtils.toString(uploadedFile.getInputStream(), "UTF-8"));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:org.openmrs.module.visitdocumentsui.ComplexObsSaver.java

public Obs saveImageDocument(Visit visit, Person person, Encounter encounter, String fileCaption,
        MultipartFile multipartFile, String instructions) throws IOException {

    conceptComplex = context.getConceptComplex(ContentFamily.IMAGE);
    prepareComplexObs(visit, person, encounter, fileCaption);

    Object image = multipartFile.getInputStream();
    double compressionRatio = getCompressionRatio(multipartFile.getSize(),
            1000000 * context.getMaxStorageFileSize());
    if (compressionRatio < 1) {
        image = Thumbnails.of(ImageIO.read(multipartFile.getInputStream())).scale(compressionRatio)
                .asBufferedImage();/*ww w. j  a  v a2 s  .  c  o  m*/
    }
    obs.setComplexData(complexDataHelper
            .build(instructions, multipartFile.getOriginalFilename(), image, multipartFile.getContentType())
            .asComplexData());
    obs = context.getObsService().saveObs(obs, getClass().toString());
    return obs;
}

From source file:com.yunmel.syncretic.core.BaseController.java

protected File uploadFile(HttpServletRequest request, String field) {
    try {//from w w w  . j  a v a2  s  .  c om
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultiValueMap<String, MultipartFile> map = multipartRequest.getMultiFileMap();
            List<MultipartFile> files = map.get(field);
            MultipartFile _file = files.get(0);
            File file = new File(RandomUtils.genRandom32Hex());
            IOUtils.copyInputStreamToFile(_file.getInputStream(), file);
            return file;
        }
    } catch (IOException e) {
        LOG.error("upload file error.", e);
    }

    return null;
}

From source file:ac.simons.tweetarchive.web.ArchiveHandlingController.java

/**
 * As you can see, it get's nasty here...
 * <br>//from  w  w  w .java  2s .  com
 * Twitter4j doesn't offer an official way to parse Twitters JSON, so I
 * brute force my way into the twitter4j.StatusJSONImpl implementation of
 * Status.
 * <br>
 * And even if there was an official way, the JSON files inside the
 * official(!) Twitter archive differ from the API, even if they are said to
 * be identical. By the way, I'm not the only one, who
 * <a href="https://twittercommunity.com/t/why-does-twitter-json-archive-have-a-different-format-than-the-rest-api-1-1/35530">noticed
 * that</a>.
 * <br>
 * Furthermore, I didn't even bother to add error handling or tests.
 *
 * @param archive The uploaded archive
 * @return Redirect to the index
 * @throws java.io.IOException
 * @throws twitter4j.JSONException
 */
@PostMapping
public String store(@NotNull final MultipartFile archive, final RedirectAttributes redirectAttributes)
        throws IOException, JSONException {
    try (final ZipInputStream archiv = new ZipInputStream(archive.getInputStream())) {
        ZipEntry entry;
        while ((entry = archiv.getNextEntry()) != null) {
            if (!entry.getName().startsWith("data/js/tweets/") || entry.isDirectory()) {
                continue;
            }
            log.debug("Reading archive entry {}...", entry.getName());
            final BufferedReader buffer = new BufferedReader(
                    new InputStreamReader(archiv, StandardCharsets.UTF_8));

            final String content = buffer.lines().skip(1).map(l -> {
                Matcher m = PATTERN_CREATED_AT.matcher(l);
                String rv = l;
                if (m.find()) {
                    try {
                        rv = m.replaceFirst(
                                "$1\"" + DATE_FORMAT_OUT.format(DATE_FORMAT_IN.parse(m.group(2))) + "\"");
                    } catch (ParseException ex) {
                        log.warn("Unexpected date format in twitter archive", ex);
                    }
                }
                return rv;
            }).collect(Collectors.joining("")).replaceAll("\"sizes\" : \\[.+?\\],", "\"sizes\" : {},");

            final JSONArray statuses = new JSONArray(content);
            for (int i = 0; i < statuses.length(); ++i) {
                final JSONObject rawJSON = statuses.getJSONObject(i);
                // https://twitter.com/lukaseder/status/772772372990586882 ;)
                final Status status = statusFactory.create(rawJSON).as(Status.class);
                this.tweetStorageService.store(status, rawJSON.toString());
            }
        }
    }
    redirectAttributes.addFlashAttribute("message", "Done.");
    return "redirect:/upload";
}

From source file:ro.cornholio.vision.text.TextApp.java

@RequestMapping(method = RequestMethod.POST, value = "/")
public String handleFileUpload(@RequestParam("file") MultipartFile file,
        RedirectAttributes redirectAttributes) {
    if (!file.isEmpty()) {
        try {//  w  ww .ja va  2  s. co  m
            byte[] bytes = IOUtils.toByteArray(file.getInputStream());
            List<ImageText> texts = detectText(bytes);
            for (ImageText txt : texts) {
                for (EntityAnnotation annotation : txt.textAnnotations()) {
                    System.out.println(annotation.getDescription());
                }
            }

            redirectAttributes.addFlashAttribute("message", "You successfully uploaded !");
        } catch (IOException | RuntimeException e) {
            redirectAttributes.addFlashAttribute("message", "Failed to upload => " + e.getMessage());
        }
    } else {
        redirectAttributes.addFlashAttribute("message", "Failed to upload because it was empty");
    }

    return "redirect:/";
}

From source file:net.longfalcon.web.AdminGameController.java

@RequestMapping(value = "/admin/console-edit", method = RequestMethod.POST)
public View editConsolePost(@ModelAttribute("consoleInfo") ConsoleInfoVO consoleInfoVo, Model model)
        throws NoSuchResourceException, FileUploadException {
    MultipartFile file = consoleInfoVo.getMultipartFile();
    long id;//from  w w  w  .  j av a 2s.  co  m
    InputStream coverStream = null;
    try {
        if (file != null && !file.isEmpty()) {
            coverStream = file.getInputStream();
        }
        ConsoleInfo consoleInfo = populateConsoleInfo(consoleInfoVo);
        gameService.updateConsoleInfo(consoleInfo, coverStream);
        id = consoleInfo.getId();
    } catch (Exception e) {
        _log.error(e, e);
        throw new FileUploadException();
    }

    return safeRedirect("/admin/console-edit?id=" + id);
}