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.devnexus.ting.web.controller.admin.OrganizerController.java

@RequestMapping(value = "/s/admin/organizer", method = RequestMethod.POST)
public String addOrganizer(@RequestParam MultipartFile pictureFile, @Valid Organizer organizerForm,
        BindingResult result, HttpServletRequest request, RedirectAttributes redirectAttributes) {

    if (request.getParameter("cancel") != null) {
        return "redirect:/s/admin/organizers";
    }//from www .  j av a  2 s. co m

    if (result.hasErrors()) {
        return "/admin/add-organizer";
    }

    if (pictureFile != null && pictureFile.getSize() > 0) {

        final FileData pictureData = new FileData();

        try {

            pictureData.setFileData(IOUtils.toByteArray(pictureFile.getInputStream()));
            pictureData.setFileSize(pictureFile.getSize());
            pictureData.setFileModified(new Date());
            pictureData.setName(pictureFile.getOriginalFilename());

        } catch (IOException e) {
            throw new IllegalStateException(
                    "Error while processing image for speaker " + organizerForm.getFirstLastName(), e);
        }

        organizerForm.setPicture(pictureData);

        String message = "File '" + organizerForm.getPicture().getName() + "' uploaded successfully";
        redirectAttributes.addFlashAttribute("successMessage", message);

    }

    Organizer savedOrganizer = businessService.saveOrganizer(organizerForm);

    redirectAttributes.addFlashAttribute("successMessage",
            String.format("The organizer '%s' was added successfully.", savedOrganizer.getFirstLastName()));

    return "redirect:/s/admin/organizers";
}

From source file:com.epam.ta.reportportal.core.user.impl.EditUserHandler.java

private void validatePhoto(MultipartFile file) throws IOException {
    expect(file.getSize() < MAX_PHOTO_SIZE, equalTo(true)).verify(BINARY_DATA_CANNOT_BE_SAVED,
            "Image size should be less than 1 mb");
    MediaType mediaType = new AutoDetectParser().getDetector().detect(TikaInputStream.get(file.getBytes()),
            new Metadata());
    String subtype = mediaType.getSubtype();
    expect(ImageFormat.fromValue(subtype), notNull()).verify(BINARY_DATA_CANNOT_BE_SAVED,
            "Image format should be " + ImageFormat.getValues());
    BufferedImage read = ImageIO.read(file.getInputStream());
    expect((read.getHeight() <= MAX_PHOTO_HEIGHT) && (read.getWidth() <= MAX_PHOTO_WIDTH), equalTo(true))
            .verify(BINARY_DATA_CANNOT_BE_SAVED, "Image size should be 300x500px or less");
}

From source file:com.indeed.iupload.web.controller.AppController.java

@RequestMapping(value = "/repository/{repoId}/index/{indexName}/file/", method = RequestMethod.POST)
public @ResponseBody BasicResponse executeCreateFile(@PathVariable String repoId,
        @PathVariable String indexName, @RequestParam("file") MultipartFile file, HttpServletRequest request)
        throws Exception {
    if (!checkUserQualification(request, repoId, indexName)) {
        throw new UnauthorizedOperationException();
    }// w w w.j  a v a 2s  .c o m
    if (file.isEmpty()) {
        return BasicResponse.error("File is not specified");
    }
    IndexRepository repository = getRepository(repoId);
    Index index = repository.find(indexName);
    InputStream is = file.getInputStream();
    try {
        index.createFileToIndex(file.getOriginalFilename(), is);
    } finally {
        Closeables2.closeQuietly(is, log);
    }
    return BasicResponse.success(null);
}

From source file:com.vsquaresystem.safedeals.rawmarketprice.RawMarketPriceService.java

@Transactional(readOnly = false)
public Boolean insertAttachments(MultipartFile attachmentMultipartFile)
        throws JsonProcessingException, IOException {
    logger.info("attachmentMultipartFile in service Line31{}", attachmentMultipartFile);
    System.out.println("attachmentMultipartFile" + attachmentMultipartFile);
    File outputFile = attachmentUtils.storeAttachmentByAttachmentType(
            attachmentMultipartFile.getOriginalFilename(), attachmentMultipartFile.getInputStream(),
            AttachmentUtils.AttachmentType.RAW_MARKET_PRICE);
    return outputFile.exists();
}

From source file:net.shopxx.plugin.abcPayment.AbcPaymentController.java

@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(String paymentName, String merchantId, MultipartFile keyFile, String keyPassword,
        PaymentPlugin.FeeType feeType, BigDecimal fee, String logo, String description,
        @RequestParam(defaultValue = "false") Boolean isEnabled, Integer order,
        RedirectAttributes redirectAttributes) {
    PluginConfig pluginConfig = abcPaymentPlugin.getPluginConfig();
    Map<String, String> attributes = new HashMap<String, String>();
    attributes.put(PaymentPlugin.PAYMENT_NAME_ATTRIBUTE_NAME, paymentName);
    attributes.put("merchantId", merchantId);
    if (keyFile != null && !keyFile.isEmpty()) {
        InputStream inputStream = null;
        try {/*from  w w w . java2s  .  co  m*/
            inputStream = keyFile.getInputStream();
            PrivateKey privateKey = (PrivateKey) RSAUtils.getKey("PKCS12", inputStream, keyPassword);
            attributes.put("key", RSAUtils.getKeyString(privateKey));
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } catch (RuntimeException e) {
            addFlashMessage(redirectAttributes, Message.warn("admin.plugin.abcPayment.keyInvalid"));
            return "redirect:setting.jhtml";
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    } else {
        attributes.put("key", pluginConfig.getAttribute("key"));
    }
    attributes.put(PaymentPlugin.FEE_TYPE_ATTRIBUTE_NAME, feeType.toString());
    attributes.put(PaymentPlugin.FEE_ATTRIBUTE_NAME, fee.toString());
    attributes.put(PaymentPlugin.LOGO_ATTRIBUTE_NAME, logo);
    attributes.put(PaymentPlugin.DESCRIPTION_ATTRIBUTE_NAME, description);
    pluginConfig.setAttributes(attributes);
    pluginConfig.setIsEnabled(isEnabled);
    pluginConfig.setOrder(order);
    pluginConfigService.update(pluginConfig);
    addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
    return "redirect:/admin/payment_plugin/list.jhtml";
}

From source file:com.laishidua.mobilecloud.ghostmyselfie.controller.GhostMySelfieController.java

/**
 * /*from  w w w.  ja  v a  2s .  c  o  m*/
 * @param id       : the id of the ghostmyselfie to associate this data stream with
 * @param ghostMyselfieData : the data stream
 * @param response   : http response, exposed to allow manipulation like setting
 *                   error codes
 * @return         : a GhostMySelfieStatus object if successful, null otherwise
 * @throws IOException
 */
@RequestMapping(value = GhostMySelfieSvcApi.GHOSTMYSELFIE_DATA_PATH, method = RequestMethod.POST)
public ResponseEntity<GhostMySelfieStatus> setGhostMySelfieData(
        @PathVariable(GhostMySelfieSvcApi.ID_PARAMETER) long id,
        @RequestPart(GhostMySelfieSvcApi.DATA_PARAMETER) MultipartFile ghostMySelfieData,
        HttpServletResponse response, Principal p) throws IOException {
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.APPLICATION_JSON);
    GhostMySelfie gms = ghostMySelphie.findOne(id);
    if (gms != null) {
        if (p.getName().equals(gms.getOwner())) {
            String mimeType = URLConnection.guessContentTypeFromStream(ghostMySelfieData.getInputStream());
            if (!mimeType.equals("image/jpeg") && !mimeType.equals("image/png")) {
                response.sendError(400, "Just jpg, jpeg and png images supported");
                return null;
            }
            ghostMySelfieDataMgr = GhostMySelfieFileManager.get();
            saveSomeGhostMySelfie(gms, ghostMySelfieData);
            return new ResponseEntity<GhostMySelfieStatus>(
                    new GhostMySelfieStatus(GhostMySelfieStatus.GhostMySelfieState.READY), responseHeaders,
                    HttpStatus.CREATED);
        } else {
            response.sendError(400, "Not your Selfie, hands off!");
            return null;
        }
    } else {
        response.sendError(404, "Your Selfie is in another castle.");
        return null;
    }
}

From source file:org.magnum.dataup.SimpleVideoSvcController.java

@RequestMapping(value = "/video/{id}/data", method = RequestMethod.POST)
public @ResponseBody VideoStatus setVideoData(@PathVariable("id") long id,
        @RequestParam("data") MultipartFile videoData, HttpServletResponse response) throws IOException {
    VideoStatus status = new VideoStatus(VideoState.READY);
    //don't have the video: return 404 - the client should receive a 404 error and throw an exception
    if (!videos.containsKey(id)) {
        //   response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return status; // if the id is invalid, the status won't be checked by the client
    }//  ww w  . j  a va  2  s  .c om

    videoFileManager = (null == videoFileManager) ? VideoFileManager.get() : videoFileManager;
    videoFileManager.saveVideoData(videos.get(id), videoData.getInputStream());
    //succesful: status.state == VideoState.READY            
    return status;
}

From source file:com.askme.controller.app.AppController.java

@RequestMapping(value = "/user/changeProfile", method = RequestMethod.POST)
public String postChangeProfile(@Valid User user, BindingResult result, ModelMap model,
        RedirectAttributes redirect, HttpServletRequest request,
        @RequestParam(value = "file", required = false) MultipartFile file) {
    passwordValidator.validate(user, result);
    if (result.hasErrors()) {
        System.out.println(result.getAllErrors());
        return "change_profile";
    }//from  w ww . ja  v  a  2s .  c om

    // Upload avatar
    if (file != null) {
        try {
            InputStream inputStream = file.getInputStream();
            if (inputStream == null) {
                System.out.println("File inputstream is null");
            }
            String path = request.getServletContext().getRealPath("/") + "public/avatar/";
            FileUtils.forceMkdir(new File(path));
            File upload = new File(path + file.getOriginalFilename());
            file.transferTo(upload);
            user.setAvatar(file.getOriginalFilename());
            IOUtils.closeQuietly(inputStream);
        } catch (IOException ex) {
            System.out.println("Error saving uploaded file");
        }
    }

    userService.update(user);

    redirect.addFlashAttribute("success", "Cp nht profile thnh cng");
    return "redirect:/login";
}