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.emergya.persistenceGeo.web.RestLayersAdminController.java

/**
 * This method saves a layer related with a user
 * //  w  w w  .  j a v a  2  s  .  c om
 * @param uploadfile
 */
@RequestMapping(value = "/persistenceGeo/uploadFile", method = RequestMethod.POST)
public ModelAndView uploadFile(@RequestParam(value = "uploadfile") MultipartFile uploadfile) {
    ModelAndView model = new ModelAndView();
    String result = null;
    if (uploadfile != null) {
        Long id = RANDOM.nextLong();
        result = "{\"results\": 1, \"data\": \"" + id + "\", \"success\": true}";
        byte[] data;
        try {
            data = IOUtils.toByteArray(uploadfile.getInputStream());
            File temp = com.emergya.persistenceGeo.utils.FileUtils.createFileTemp("tmp", "xml");
            org.apache.commons.io.FileUtils.writeByteArrayToFile(temp, data);
            loadFiles.put(id, temp);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        result = "{\"results\": 0, \"data\": \"\", \"success\": false}";
    }
    model.addObject("resultado", result);
    model.setViewName("resultToJSON");
    return model;
}

From source file:net.duckling.ddl.web.api.rest.FileEditController.java

@RequestMapping(value = "/files", method = RequestMethod.POST)
public void upload(@RequestParam(value = "path", required = false) String path,
        @RequestParam("file") MultipartFile file,
        @RequestParam(value = "ifExisted", required = false) String ifExisted, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    String uid = getCurrentUid(request);
    int tid = getCurrentTid();
    path = StringUtils.defaultIfBlank(path, PathName.DELIMITER);

    Resource parent = folderPathService.getResourceByPath(tid, path);
    if (parent == null) {
        writeError(ErrorMsg.NOT_FOUND, response);
        return;/*from  w w w  . j av a 2 s  .co m*/
    }

    List<Resource> list = resourceService.getResourceByTitle(tid, parent.getRid(), LynxConstants.TYPE_FILE,
            file.getOriginalFilename());
    if (list.size() > 0 && !IF_EXISTED_UPDATE.equals(ifExisted)) {
        writeError(ErrorMsg.EXISTED, response);
        return;
    }

    FileVersion fv = null;
    try {
        fv = resourceOperateService.upload(uid, super.getCurrentTid(), parent.getRid(),
                file.getOriginalFilename(), file.getSize(), file.getInputStream());
    } catch (NoEnoughSpaceException e) {
        writeError(ErrorMsg.NO_ENOUGH_SPACE, response);
        return;
    }

    Resource resource = resourceService.getResource(fv.getRid());
    resource.setPath(folderPathService.getPathString(resource.getRid()));
    JsonUtil.write(response, VoUtil.getResourceVo(resource));
}

From source file:com.zte.gu.webtools.web.ddm.DdmController.java

@RequestMapping(method = RequestMethod.POST)
public ModelAndView scan(@RequestParam(required = true) MultipartFile boardFile,
        @RequestParam(required = true) MultipartFile ruFile, @RequestParam(required = true) String sdrVer,
        HttpSession session) {//from  ww  w  .  java  2 s.co m
    List<DdmVersion> versions = ddmService.getAllVersion();
    ModelAndView modelAndView = new ModelAndView("ddm/ddmScan");
    modelAndView.getModelMap().addAttribute("versions", versions);
    if (boardFile.isEmpty()) {
        modelAndView.getModelMap().addAttribute("error", "?");
    }
    if (!ACCEPT_TYPES.contains(boardFile.getContentType())) {
        modelAndView.getModelMap().addAttribute("error", "???");
    }
    if (ruFile.isEmpty()) {
        modelAndView.getModelMap().addAttribute("error", "RU?");
    }
    if (!ACCEPT_TYPES.contains(ruFile.getContentType())) {
        modelAndView.getModelMap().addAttribute("error", "RU???");
    }

    InputStream boardInput = null;
    InputStream ruInput = null;
    try {
        boardInput = boardFile.getInputStream();
        ruInput = ruFile.getInputStream();
        File tempZipFile = ddmService.exportXml(boardInput, ruInput, sdrVer); //?
        if (tempZipFile != null) {
            session.setAttribute("filePath", tempZipFile.getPath());
            session.setAttribute("fileName", "ddm.zip");
            modelAndView.setViewName("redirect:/download");
        }
    } catch (Exception e) {
        LoggerFactory.getLogger(DdmController.class).warn("download error,", e);
        modelAndView.getModelMap().addAttribute("error", "?" + e.getMessage());
    } finally {
        IOUtils.closeQuietly(boardInput);
        IOUtils.closeQuietly(ruInput);
    }
    return modelAndView;
}

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

/**
 * update the object requested//w  ww  . jav  a 2  s. c om
 *
 * @param request
 * @param response
 * @param pid
 * @throws InvalidToken
 * @throws ServiceFailure
 * @throws IOException
 * @throws NotAuthorized
 * @throws NotFound
 * @throws NotImplemented
 */
@RequestMapping(value = "/v1/object/{pid}", method = RequestMethod.PUT)
public void update(MultipartHttpServletRequest fileRequest, HttpServletResponse response,
        @PathVariable String pid)
        throws InvalidToken, ServiceFailure, IOException, NotAuthorized, NotFound, NotImplemented,
        InvalidRequest, InsufficientResources, InvalidSystemMetadata, IdentifierNotUnique, UnsupportedType {

    debugRequest(fileRequest);
    Identifier id = new Identifier();
    try {
        id.setValue(urlCodec.decode(pid, "UTF-8"));
    } catch (DecoderException ex) {
        throw new ServiceFailure("20000", ex.getMessage());
    } catch (UnsupportedEncodingException ex) {
        throw new ServiceFailure("20001", ex.getMessage());
    }
    if (!this.logRequest(fileRequest, Event.UPDATE, id)) {

        throw new ServiceFailure("20001", "unable to log request");
    }
    Session session = new Session();
    InputStream objectInputStream = null;
    MultipartFile sytemMetaDataMultipart = null;
    MultipartFile objectMultipart = null;

    SystemMetadata systemMetadata = null;
    Set<String> keys = fileRequest.getFileMap().keySet();
    for (String key : keys) {
        if (key.equalsIgnoreCase("sysmeta")) {
            sytemMetaDataMultipart = fileRequest.getFileMap().get(key);
        } else {
            objectMultipart = fileRequest.getFileMap().get(key);
        }
    }
    if (sytemMetaDataMultipart != null) {
        try {

            systemMetadata = (SystemMetadata) TypeMarshaller.unmarshalTypeFromStream(SystemMetadata.class,
                    sytemMetaDataMultipart.getInputStream());
        } catch (IOException ex) {
            throw new InvalidSystemMetadata("15001", ex.getMessage());
        } catch (JiBXException ex) {
            throw new InvalidSystemMetadata("15002", ex.getMessage());
        } catch (InstantiationException ex) {
            throw new InvalidSystemMetadata("15003", ex.getMessage());
        } catch (IllegalAccessException ex) {
            throw new InvalidSystemMetadata("15004", ex.getMessage());
        }
    } else {
        throw new InvalidSystemMetadata("15005",
                "System Metadata was not found as Part of Multipart Mime message");
    }
    if (objectMultipart != null && !(objectMultipart.isEmpty())) {
        try {
            objectInputStream = objectMultipart.getInputStream();
        } catch (IOException ex) {
            throw new InvalidRequest("15006", ex.getMessage());
        }
    } else {
        throw new InvalidRequest("15007", "Object to be created is not attached");
    }

    id.setValue(systemMetadata.getIdentifier().getValue());

    DateTime dt = new DateTime();
    systemMetadata.setDateSysMetadataModified(dt.toDate());

    mnStorage.update(id, null, id, null);
    InputStream in = mnRead.get(id);
    OutputStream out = response.getOutputStream();
    try {

        byte[] buffer = null;
        int filesize = in.available();
        if (filesize < 250000) {
            buffer = new byte[SMALL_BUFF_SIZE];
        } else if (filesize >= 250000 && filesize <= 500000) {
            buffer = new byte[MED_BUFF_SIZE];
        } else {
            buffer = new byte[LARGE_BUFF_SIZE];
        }
        while (true) {
            int amountRead = in.read(buffer);
            if (amountRead == -1) {
                break;
            }
            out.write(buffer, 0, amountRead);
            out.flush();
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.flush();
            out.close();
        }

    }
}

From source file:org.opentravel.pubs.controllers.AdminController.java

@RequestMapping({ "/DoUploadCodeList.html", "/DoUploadCodeList.htm" })
public String doUploadCodeListPage(HttpSession session, Model model, RedirectAttributes redirectAttrs,
        @ModelAttribute("codeListForm") CodeListForm codeListForm,
        @RequestParam(value = "archiveFile", required = false) MultipartFile archiveFile) {
    String targetPage = "uploadCodeList";
    try {/*from  ww  w  .ja  v  a2s  .  co  m*/
        if (codeListForm.isProcessForm()) {
            CodeList codeList = new CodeList();

            try {
                codeList.setReleaseDate(CodeList.labelFormat.parse(codeListForm.getReleaseDateLabel()));

                if (!archiveFile.isEmpty()) {
                    DAOFactoryManager.getFactory().newCodeListDAO().publishCodeList(codeList,
                            archiveFile.getInputStream());

                    model.asMap().clear();
                    redirectAttrs.addAttribute("releaseDate", codeList.getReleaseDateLabel());
                    targetPage = "redirect:/admin/ViewCodeList.html";

                } else {
                    ValidationResults vResults = ModelValidator.validate(codeList);

                    // An archive file must be provided on initial creation of a publication
                    vResults.add(codeList, "archiveFilename", "Archive File is Required");

                    if (vResults.hasViolations()) {
                        throw new ValidationException(vResults);
                    }
                }

            } catch (ParseException e) {
                ValidationResults vResult = new ValidationResults();

                vResult.add(codeList, "releaseDate", "Invalid release date");
                addValidationErrors(vResult, model);

            } catch (ValidationException e) {
                addValidationErrors(e, model);

            } catch (Throwable t) {
                log.error("An error occurred while publishing the code list: ", t);
                setErrorMessage(t.getMessage(), model);
            }
        }

    } catch (Throwable t) {
        log.error("Error during publication controller processing.", t);
        setErrorMessage(DEFAULT_ERROR_MESSAGE, model);
    }
    return applyCommonValues(model, targetPage);
}

From source file:com.mycompany.projetsportmanager.spring.rest.controllers.UserController.java

/**
 * Affect a image to a specified user/*from   w  ww  .j av  a  2s .com*/
 * 
 * @param userId
 *            the user identifier
 * @param uploadedInputStream
 *            the image uploaded input stream
 * @param fileDetail
 *            the image detail format
 * @return response
 */
@RequestMapping(method = RequestMethod.POST, value = "/{userId}/picture")
@ResponseStatus(HttpStatus.OK)
@PreAuthorize(value = "hasRole('AK_ADMIN')")
public void pictureUpdate(@PathVariable("userId") Long userId, @RequestParam MultipartFile user_picture) {

    //Le nom du paramtre correspond au nom du champ de formulaire qu'il faut utiliser !!!!

    if (user_picture == null || user_picture.isEmpty()) {
        logger.debug("Incorrect input stream or file name for image of user" + userId);
        throw new DefaultSportManagerException(new ErrorResource("parameter missing",
                "Picture should be uploaded as a multipart/form-data file param named user_picture",
                HttpStatus.BAD_REQUEST));
    }

    if (!(user_picture.getOriginalFilename().endsWith(".jpg")
            || user_picture.getOriginalFilename().endsWith(".jpeg"))) {
        logger.debug("File for picture of user" + userId + " must be a JPEG file.");
        throw new DefaultSportManagerException(new ErrorResource("incorrect file format",
                "Picture should be a JPG file", HttpStatus.BAD_REQUEST));
    }

    try {
        userService.addUserPicture(userId, user_picture.getInputStream());
    } catch (SportManagerException e) {
        String msg = "Can't update user picture with id " + userId + " into DB";
        logger.error(msg, e);
        throw new DefaultSportManagerException(
                new ErrorResource("db error", msg, HttpStatus.INTERNAL_SERVER_ERROR));
    } catch (IOException e) {
        String msg = "Can't update user picture with id " + userId + " because of IO Error";
        logger.error(msg, e);
        throw new DefaultSportManagerException(
                new ErrorResource("io error", msg, HttpStatus.INTERNAL_SERVER_ERROR));
    }
}

From source file:com.cloud.ops.resource.ResourcePackageController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody//www.j av  a2s .c  om
public ResourcePackage uploadWar(@RequestParam("file") MultipartFile file,
        @RequestParam("version") String version, @RequestParam("type") String type,
        @RequestParam("applicationId") String applicationId) {
    final ResourcePackage resourcePackage = new ResourcePackage();
    resourcePackage.setType(ResourcePackageType.valueOf(type));
    resourcePackage.setName(version);
    resourcePackage.setVersion(version);
    resourcePackage.setApplicationId(applicationId);
    if (file != null && !file.getOriginalFilename().trim().equals("")) {
        String uploadPath = PACKAGE_FILE_PATH + File.separator + UUID.randomUUID().toString() + File.separator;
        String fileName = file.getOriginalFilename();
        final String filePath = uploadPath + fileName;
        resourcePackage.setStatus(ResourcePackageStatus.SAVING);
        service.create(resourcePackage);
        new ThreadWithEntity<ResourcePackage>(resourcePackage) {
            @Override
            public void run(ResourcePackage entity) {
                File destination = new File(filePath);
                try {
                    fileStore.storeFile(file.getInputStream(), filePath);
                } catch (IOException e) {
                    throw new OpsException("?war?", e);
                }
                entity.setWarPath(destination.getAbsolutePath());
                entity.setStatus(ResourcePackageStatus.FINISH);
                service.create(entity);
                webSocketHandler.sendMsg(PACKAGE_STATUS, entity);
            }
        }.start();
    } else {
        throw new OpsException("war?");
    }
    return resourcePackage;
}

From source file:org.kievguide.controller.PlaceController.java

@RequestMapping(value = "/addnewplace", method = RequestMethod.POST)
public ModelAndView addNewPlace(HttpServletRequest request,
        @CookieValue(value = "userstatus", defaultValue = "guest") String useremail,
        @RequestParam("placename") String placename, @RequestParam("placedescription") String placedescription,
        @RequestParam("placeadress") String placeadress, @RequestParam("placemetro") Integer placemetro,
        @RequestParam("placephotosrc") MultipartFile file) throws IOException {
    ModelAndView modelAndView = new ModelAndView();
    SecureRandom random = new SecureRandom();
    String photoname = new BigInteger(130, random).toString(32);
    Place place = new Place();
    User user = userService.searchUser(useremail);
    Station metroStation = stationService.findById(placemetro);

    System.out.println("========================================== metro = " + metroStation.getName());

    place.setName(placename);/*from   w  w  w .  j  a  v  a  2  s  .  c  o m*/
    place.setDescription(placedescription);
    place.setAdress(placeadress);
    place.setMetro(metroStation);
    place.setAuthorid(user);
    place.setPhotosrc("img/" + photoname + ".jpg");
    place.setRatingcount(0);
    place.setRatingvalue(0.0);
    String folder = request.getSession().getServletContext().getRealPath("");
    folder = folder.substring(0, 30);
    BufferedOutputStream stream = new BufferedOutputStream(
            new FileOutputStream(new File(folder + "/src/main/webapp/img/" + photoname + ".jpg")));
    FileCopyUtils.copy(file.getInputStream(), stream);
    stream.close();
    System.out.println(
            "========================================== ? ? = " + place.getName());
    placeService.addPlace(place);

    return new ModelAndView("redirect:" + "firstrequest");
}

From source file:de.steilerdev.myVerein.server.model.GridFSRepository.java

public GridFSFile storeClubLogo(MultipartFile clubLogoFile) throws MongoException {
    if (!clubLogoFile.getContentType().startsWith("image")) {
        logger.warn("Trying to store a club logo, which is not an image");
        throw new MongoException("The file needs to be an image");
    } else if (!(clubLogoFile.getContentType().equals("image/jpeg")
            || clubLogoFile.getContentType().equals("image/png"))) {
        logger.warn("Trying to store an incompatible image " + clubLogoFile.getContentType());
        throw new MongoException("The used image is not compatible, please use only PNG or JPG files");
    } else {/*from   ww  w .j a  v  a  2s  .  c  om*/
        File clubLogoTempFile = null;
        try {
            clubLogoTempFile = File.createTempFile("tempClubLogo", "png");
            clubLogoTempFile.deleteOnExit();
            if (clubLogoFile.getContentType().equals("image/png")) {
                logger.debug("No need to convert club logo");
                clubLogoFile.transferTo(clubLogoTempFile);
            } else {
                logger.info("Converting club logo file to png");
                //Reading, converting and writing club logo
                ImageIO.write(ImageIO.read(clubLogoFile.getInputStream()), clubLogoFileFormat,
                        clubLogoTempFile);
            }

            //Deleting current file
            deleteCurrentClubLogo();

            try (FileInputStream clubLogoStream = new FileInputStream(clubLogoTempFile)) {
                logger.debug("Saving club logo");
                //Saving file
                return gridFS.store(clubLogoStream, clubLogoFileName, clubLogoFileFormatMIME);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new MongoException("Unable to store file");
        } finally {
            if (clubLogoTempFile != null) {
                clubLogoTempFile.delete();
            }
        }
    }
}