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:fr.olympicinsa.riocognized.ImageController.java

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(@ModelAttribute("image") Image image, @RequestParam("file") MultipartFile file) {

    System.out.println("Name:" + image.getName());
    System.out.println("Desc:" + image.getDescription());
    System.out.println("File:" + file.getName());
    System.out.println("ContentType:" + file.getContentType());

    try {//from w ww  .jav a 2 s .c o  m
        byte[] blob = IOUtils.toByteArray(file.getInputStream());

        image.setFilename(file.getOriginalFilename());
        image.setContent(blob);
        image.setContentType(file.getContentType());
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        imageRepository.save(image);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return "redirect:/image";
}

From source file:org.wte4j.ui.server.services.TemplateRestService.java

/**
 * processes template file upload and save the file on the server side in
 * temp folder. returns the path/*from  www . java 2s  .  c o m*/
 * 
 * @param file
 * @return
 */
@RequestMapping(value = "temp", method = RequestMethod.POST, produces = "text/html; charset=UTF-8")
public String uploadFile(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) {
    if (file.isEmpty()) {
        throw new WteFileUploadException(MessageKey.UPLOADED_FILE_NOT_READABLE);
    }
    try {
        File tempFile = File.createTempFile(name, ".docx");
        try (OutputStream out = new FileOutputStream(tempFile); InputStream in = file.getInputStream()) {
            IOUtils.copy(in, out);
            FileUploadResponseDto response = new FileUploadResponseDto();
            response.setDone(true);
            response.setMessage(tempFile.toString());
            return fileUploadResponseFactory.toJson(response);
        }
    } catch (IOException e) {
        throw new WteFileUploadException(MessageKey.UPLOADED_FILE_NOT_READABLE);
    }
}

From source file:com.capstone.giveout.controllers.GiftsController.java

private void saveImages(Gift gift, MultipartFile image) throws IOException {
    if (image == null || image.isEmpty())
        return;//from  www.  j  a  va2  s. c o  m

    BufferedImage img = ImageIO.read(image.getInputStream());
    ImageFileManager imgMan = ImageFileManager.get(GIFT_ROOT_PATH);

    imgMan.saveImage(gift.getId(), Gift.SIZE_FULL, img);
    gift.setImageUrlFull(Routes.GIFTS_IMAGE_PATH.replace("{id}", String.valueOf(gift.getId())).replace("{size}",
            Gift.SIZE_FULL));

    BufferedImage scaledImg = Scalr.resize(img, 640);
    imgMan.saveImage(gift.getId(), Gift.SIZE_MEDIUM, scaledImg);
    gift.setImageUrlMedium(Routes.GIFTS_IMAGE_PATH.replace("{id}", String.valueOf(gift.getId()))
            .replace("{size}", Gift.SIZE_MEDIUM));

    scaledImg = Scalr.resize(img, 320);
    imgMan.saveImage(gift.getId(), Gift.SIZE_SMALL, scaledImg);
    gift.setImageUrlSmall(Routes.GIFTS_IMAGE_PATH.replace("{id}", String.valueOf(gift.getId()))
            .replace("{size}", Gift.SIZE_SMALL));

    gifts.save(gift);
}

From source file:fr.olympicinsa.riocognized.AdvertController.java

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(@ModelAttribute("image") ImagePub image, @RequestParam("file") MultipartFile file) {

    System.out.println("Name:" + image.getName());
    System.out.println("Desc:" + image.getDescription());
    System.out.println("File:" + file.getName());
    System.out.println("ContentType:" + file.getContentType());

    try {/*from  ww w. ja v a  2s.com*/
        byte[] blob = IOUtils.toByteArray(file.getInputStream());

        image.setFilename(file.getOriginalFilename());
        image.setContent(blob);
        image.setContentType(file.getContentType());
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        imagePubRepository.save(image);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return "redirect:/ad/manage";
}

From source file:fr.esiea.esieaddress.controllers.importation.CSVImportCtrl.java

@RequestMapping(method = RequestMethod.POST)
@ResponseBody//from   w w  w. ja  v a  2s  .  c  om
@Secured("ROLE_USER")
public void upload(MultipartHttpServletRequest files, final HttpServletRequest request)
        throws DaoException, ServiceException, FileNotFoundException {
    LOGGER.info("[IMPORT] Start to import contact");

    //TODO Make it less verbose and may use a buffer to make it safer
    Map<String, MultipartFile> multipartFileMap = files.getMultiFileMap().toSingleValueMap();
    Set<String> fileNames = multipartFileMap.keySet();

    for (String fileName : fileNames) {

        MultipartFile multipartFile = multipartFileMap.get(fileName);
        String originalFilename = multipartFile.getOriginalFilename();

        if (checkFileName(originalFilename) && multipartFile.getSize() < FILE_SIZE_MAX) {

            InputStream inputStream = null;

            try {
                inputStream = multipartFile.getInputStream();
            } catch (IOException e) {
                throw new FileNotFoundException(e.toString());
            }

            try (Reader contactsFile = new InputStreamReader(inputStream)) {
                Map<String, Object> modelErrors = new HashMap<>();
                LOGGER.debug("[IMPORT] File is reading");
                Collection<Contact> contacts = csvService.ReadContactCSV(contactsFile);
                for (Contact contact : contacts) {
                    try {
                        contactCrudService.insert(contact);
                    } catch (ValidationException e) {
                        Object modelError = e.getModel();
                        LOGGER.warn("found an error in contact " + modelError);
                        modelErrors.put(contact.getId(), (Map) modelError);
                    }
                }

                if (!modelErrors.isEmpty())
                    throw new ValidationException(modelErrors);
            } catch (IOException e) {
                throw new FileNotFoundException(e.toString());
            } finally {
                if (inputStream != null)
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        LOGGER.error("[IMPORT] Impossible to close the file " + inputStream.toString());
                    }
            }
        }
    }
}

From source file:org.openmeetings.servlet.outputhandler.UploadController.java

@RequestMapping(value = "/upload.upload", method = RequestMethod.POST)
public void handleFormUpload(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {/*from w ww.j a  va  2 s  .  c  om*/
        UploadInfo info = validate(request, false);
        LinkedHashMap<String, Object> hs = prepareMessage(info);
        String room_id = request.getParameter("room_id");
        if (room_id == null) {
            room_id = "default";
        }
        String roomName = StringUtils.deleteWhitespace(room_id);

        String moduleName = request.getParameter("moduleName");
        if (moduleName == null) {
            moduleName = "nomodule";
        }
        if (moduleName.equals("nomodule")) {
            log.debug("module name missed");
            return;
        }
        boolean userProfile = moduleName.equals("userprofile");

        MultipartFile multipartFile = info.file;
        InputStream is = multipartFile.getInputStream();
        String fileSystemName = info.filename;
        fileSystemName = StringUtils.deleteWhitespace(fileSystemName);

        // Flash cannot read the response of an upload
        // httpServletResponse.getWriter().print(returnError);
        uploadFile(request, userProfile, info.userId, roomName, is, fileSystemName, hs);
        sendMessage(info, hs);
    } catch (ServletException e) {
        throw e;
    } catch (Exception e) {
        log.error("Exception during upload: ", e);
        throw new ServletException(e);
    }
}

From source file:org.zlogic.vogon.web.controller.DataController.java

/**
 * Imports uploaded XML data// w  w  w.j  a  v a  2s  . c om
 *
 * @param data the file to import
 * @param userPrincipal the authenticated user
 * @return true of import succeeded
 */
@RequestMapping(value = "/import", method = RequestMethod.POST, produces = "application/json", consumes = "multipart/form-data")
public @ResponseBody Boolean importData(@RequestParam("file") MultipartFile data,
        @AuthenticationPrincipal VogonSecurityUser userPrincipal) throws RuntimeException {
    VogonUser user = userRepository.findByUsernameIgnoreCase(userPrincipal.getUsername());
    try {
        XmlImporter importer = new XmlImporter(data.getInputStream());
        importer.importData(user, em);
    } catch (IOException | VogonImportException | VogonImportLogicalException ex) {
        throw new RuntimeException(ex);
    }
    return true;
}

From source file:com.aerospike.client.rest.RESTController.java

@RequestMapping(value = "/uploadFlights", method = RequestMethod.POST)
public @ResponseBody String handleFileUpload(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file) {

    if (!file.isEmpty()) {
        try {/*from www .  j  a v a 2 s  .  c o m*/
            WritePolicy wp = new WritePolicy();
            String line = "";
            BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream()));
            while ((line = br.readLine()) != null) {

                // use comma as separator
                String[] flight = line.split(",");

                /*
                 * write the record to Aerospike
                 * NOTE: Bin names must not exceed 14 characters
                 */
                client.put(wp, new Key("test", "flights", flight[0].trim()),
                        new Bin("YEAR", Integer.parseInt(flight[1].trim())),
                        new Bin("DAY_OF_MONTH", Integer.parseInt(flight[2].trim())),
                        new Bin("FL_DATE", flight[3].trim()),
                        new Bin("AIRLINE_ID", Integer.parseInt(flight[4].trim())),
                        new Bin("CARRIER", flight[5].trim()),
                        new Bin("FL_NUM", Integer.parseInt(flight[6].trim())),
                        new Bin("ORI_AIRPORT_ID", Integer.parseInt(flight[7].trim())),
                        new Bin("ORIGIN", flight[8].trim()), new Bin("ORI_CITY_NAME", flight[9].trim()),
                        new Bin("ORI_STATE_ABR", flight[10].trim()), new Bin("DEST", flight[11].trim()),
                        new Bin("DEST_CITY_NAME", flight[12].trim()),
                        new Bin("DEST_STATE_ABR", flight[13].trim()),
                        new Bin("DEP_TIME", Integer.parseInt(flight[14].trim())),
                        new Bin("ARR_TIME", Integer.parseInt(flight[15].trim())),
                        new Bin("ELAPSED_TIME", Integer.parseInt(flight[16].trim())),
                        new Bin("AIR_TIME", Integer.parseInt(flight[17].trim())),
                        new Bin("DISTANCE", Integer.parseInt(flight[18].trim())));

                log.debug("Flight [ID= " + flight[0] + " , year=" + flight[1] + " , DAY_OF_MONTH=" + flight[2]
                        + " , FL_DATE=" + flight[3] + " , AIRLINE_ID=" + flight[4] + " , CARRIER=" + flight[5]
                        + " , FL_NUM=" + flight[6] + " , ORIGIN_AIRPORT_ID=" + flight[7] + "]");

            }
            br.close();
            log.info("Successfully uploaded " + name);
            return "You successfully uploaded " + name;
        } catch (Exception e) {
            log.error("Failed to upload " + name, e);
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        log.info("Failed to upload " + name + " because the file was empty.");
        return "You failed to upload " + name + " because the file was empty.";
    }
}

From source file:com.caocao.web.control.DriverManageController.java

@RequestMapping(value = "/driverimport")
@ResponseBody//  w w  w  .j a  v a 2 s. c om
public String DriversImport(MultipartHttpServletRequest execlFile, ModelMap map) {
    MultipartFile uploadfile = execlFile.getFile("execlFile");
    InputStream is;
    String fileName = uploadfile.getOriginalFilename();
    String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
    if ("xls".equals(fileSuffix)) {
        try {
            is = uploadfile.getInputStream();
            String errors = driverManageService.DriversImport(is, "xls");
            map.put("errors", errors);
        } catch (IOException e) {
            map.put("errors", e.getMessage());
        }
    }
    return "jsp";
}

From source file:org.openmeetings.servlet.outputhandler.UploadController.java

@RequestMapping(value = "/file.upload", method = RequestMethod.POST)
public void handleFileUpload(HttpServletRequest request, HttpServletResponse response, HttpSession session)
        throws ServletException {
    UploadInfo info = validate(request, false);
    try {//from  w  w  w  .j  a v  a2s.  c  o  m
        LinkedHashMap<String, Object> hs = prepareMessage(info);
        String room_idAsString = request.getParameter("room_id");
        if (room_idAsString == null) {
            throw new ServletException("Missing Room ID");
        }

        Long room_id_to_Store = Long.parseLong(room_idAsString);

        String isOwnerAsString = request.getParameter("isOwner");
        if (isOwnerAsString == null) {
            throw new ServletException("Missing isOwnerAsString");
        }
        boolean isOwner = false;
        if (isOwnerAsString.equals("1")) {
            isOwner = true;
        }

        String parentFolderIdAsString = request.getParameter("parentFolderId");
        if (parentFolderIdAsString == null) {
            throw new ServletException("Missing parentFolderId ID");
        }
        Long parentFolderId = Long.parseLong(parentFolderIdAsString);

        String current_dir = context.getRealPath("/");

        MultipartFile multipartFile = info.file;
        InputStream is = multipartFile.getInputStream();
        log.debug("fileSystemName: " + info.filename);

        HashMap<String, HashMap<String, String>> returnError = fileProcessor.processFile(info.userId,
                room_id_to_Store, isOwner, is, parentFolderId, info.filename, current_dir, hs, 0L, ""); // externalFilesId,
        // externalType

        HashMap<String, String> returnAttributes = returnError.get("returnAttributes");

        // Flash cannot read the response of an upload
        // httpServletResponse.getWriter().print(returnError);
        hs.put("message", "library");
        hs.put("action", "newFile");
        hs.put("fileExplorerItem", fileExplorerItemDao.getFileExplorerItemsById(
                Long.parseLong(returnAttributes.get("fileExplorerItemId").toString())));
        hs.put("error", returnError);
        hs.put("fileName", returnAttributes.get("completeName"));
        sendMessage(info, hs);
    } catch (ServletException e) {
        throw e;
    } catch (Exception e) {
        log.error("Exception during upload: ", e);
        throw new ServletException(e);
    }
}