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.osc.edu.chapter4.customers.CustomersController.java

@RequestMapping("/insertCustomers")
public String insertCustomers(@RequestParam(value = "imgFile", required = false) MultipartFile imgFile,
        @ModelAttribute @Valid CustomersDto customers, BindingResult results, SessionStatus status,
        HttpSession session) {//from  w w w .  j  ava  2s  . c  o  m

    if (results.hasErrors()) {
        logger.debug("results : [{}]", results);
        return "customers/form";
    }

    try {
        if (imgFile != null && !imgFile.getOriginalFilename().equals("")) {
            String fileName = imgFile.getOriginalFilename();
            String destDir = session.getServletContext().getRealPath("/upload");

            File dirPath = new File(destDir);
            if (!dirPath.exists()) {
                boolean created = dirPath.mkdirs();
                if (!created) {
                    throw new Exception("Fail to create a directory for movie image. [" + destDir + "]");
                }
            }

            IOUtils.copy(imgFile.getInputStream(), new FileOutputStream(new File(destDir, fileName)));

            logger.debug("Upload file({}) saved to [{}].", fileName, destDir);
        }

        customersService.insertCustomers(customers);
        status.setComplete();
    } catch (Exception e) {
        logger.debug("Exception has occurred. ", e);
    }

    return "redirect:/customers/getCustomersList.do";
}

From source file:com.osc.edu.chapter4.employees.EmployeesController.java

@RequestMapping("/insertEmployees")
public String insertEmployees(@RequestParam(value = "imgFile", required = false) MultipartFile imgFile,
        @ModelAttribute @Valid EmployeesDto employees, BindingResult results, SessionStatus status,
        HttpSession session) {//from  w  w w  . j a va2  s .  c om

    if (results.hasErrors()) {
        logger.debug("results : [{}]", results);
        return "employees/form";
    }

    try {
        if (imgFile != null && !imgFile.getOriginalFilename().equals("")) {
            String fileName = imgFile.getOriginalFilename();
            String destDir = session.getServletContext().getRealPath("/upload");

            File dirPath = new File(destDir);
            if (!dirPath.exists()) {
                boolean created = dirPath.mkdirs();
                if (!created) {
                    throw new Exception("Fail to create a directory for movie image. [" + destDir + "]");
                }
            }

            IOUtils.copy(imgFile.getInputStream(), new FileOutputStream(new File(destDir, fileName)));

            logger.debug("Upload file({}) saved to [{}].", fileName, destDir);
        }

        employeesService.insertEmployees(employees);
        status.setComplete();
    } catch (Exception e) {
        logger.debug("Exception has occurred. ", e);
    }

    return "redirect:/employees/getEmployeesList.do";
}

From source file:com.osc.edu.chapter4.employees.EmployeesController.java

@RequestMapping("/updateEmployees")
public String updateEmployees(@RequestParam(value = "imgFile", required = false) MultipartFile imgFile,
        @ModelAttribute @Valid EmployeesDto employees, BindingResult results, SessionStatus status,
        HttpSession session) {/*  w  ww.  j a v  a  2s  .  co  m*/

    if (results.hasErrors()) {
        logger.debug("results : [{}]", results);
        return "employees/form";
    }

    try {
        if (imgFile != null && !imgFile.getOriginalFilename().equals("")) {
            String fileName = imgFile.getOriginalFilename();
            String destDir = session.getServletContext().getRealPath("/upload");

            File dirPath = new File(destDir);
            if (!dirPath.exists()) {
                boolean created = dirPath.mkdirs();
                if (!created) {
                    throw new Exception("Fail to create a directory for movie image. [" + destDir + "]");
                }
            }

            IOUtils.copy(imgFile.getInputStream(), new FileOutputStream(new File(destDir, fileName)));

            logger.debug("Upload file({}) saved to [{}].", fileName, destDir);
        }

        employeesService.updateEmployees(employees);
        status.setComplete();
    } catch (Exception e) {
        logger.debug("Exception has occurred. ", e);
    }

    return "redirect:/employees/getEmployeesList.do";
}

From source file:org.broadleafcommerce.admin.util.controllers.FileUploadController.java

protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws ServletException, IOException {

    // cast the bean
    FileUploadBean bean = (FileUploadBean) command;

    // let's see if there's content there
    MultipartFile file = bean.getFile();
    if (file == null) {
        // hmm, that's strange, the user did not upload anything
    }/* www.  j  a v a 2 s.  com*/

    try {
        String basepath = request.getPathTranslated().substring(0,
                request.getPathTranslated().indexOf(File.separator + "upload"));
        String absoluteFilename = basepath + File.separator + bean.getDirectory() + File.separator
                + file.getOriginalFilename();
        FileSystemResource fileResource = new FileSystemResource(absoluteFilename);

        checkDirectory(basepath + File.separator + bean.getDirectory());

        backupExistingFile(fileResource, basepath + bean.getDirectory());

        FileOutputStream fout = new FileOutputStream(new FileSystemResource(
                basepath + File.separator + bean.getDirectory() + File.separator + file.getOriginalFilename())
                        .getFile());
        BufferedOutputStream bout = new BufferedOutputStream(fout);
        BufferedInputStream bin = new BufferedInputStream(file.getInputStream());
        int x;
        while ((x = bin.read()) != -1) {
            bout.write(x);
        }
        bout.flush();
        bout.close();
        bin.close();
        return super.onSubmit(request, response, command, errors);
    } catch (Exception e) {
        //Exception occured;
        e.printStackTrace();
        throw new RuntimeException(e);
        // return null;                
    }
}

From source file:com.orange.mmp.midlet.MidletManager.java

/**
 * Deploy an uploaded Midlet archive on PFS
 * @param uploadedFile The updloaded PFM file (MultipartFile to copy)
 *///from w  ww  .  j  av  a2 s  .c  o m
public void deployMidlet(MultipartFile uploadedFile) throws MMPException {
    String fileName = uploadedFile.getOriginalFilename();
    File dstFile = new File(System.getProperty("java.io.tmpdir"), fileName);
    //Try to create file
    InputStream input = null;
    OutputStream output = null;
    try {
        input = uploadedFile.getInputStream();
        output = new FileOutputStream(dstFile);
        IOUtils.copy(input, output);
    } catch (IOException ioe) {
        throw new MMPException("Failed to deploy PFM", ioe);
    } finally {
        try {
            if (input != null)
                input.close();
            if (output != null)
                output.close();
        } catch (IOException ioe) {
            //NOP
        }
    }
    this.deployMidlet(dstFile);
}

From source file:net.nan21.dnet.core.web.controller.upload.FileUploadController.java

/**
 * Generic file upload. Expects an uploaded file and a handler alias to
 * delegate the uploaded file processing.
 * /*  ww  w . j a  v a2 s  . c o  m*/
 * @param handler
 *            spring bean alias of the
 *            {@link net.nan21.dnet.core.api.service.IFileUploadService}
 *            which should process the uploaded file
 * @param file
 *            Uploaded file
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/{handler}", method = RequestMethod.POST)
@ResponseBody
public String fileUpload(@PathVariable("handler") String handler, @RequestParam("file") MultipartFile file,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    if (logger.isInfoEnabled()) {
        logger.info("Processing file upload request with-handler {} ", new String[] { handler });
    }

    if (file.isEmpty()) {
        throw new Exception("Upload was not succesful. Try again please.");
    }

    this.prepareRequest(request, response);

    IFileUploadService srv = this.getFileUploadService(handler);
    Map<String, String> paramValues = new HashMap<String, String>();

    for (String p : srv.getParamNames()) {
        paramValues.put(p, request.getParameter(p));
    }

    IUploadedFileDescriptor fileDescriptor = new UploadedFileDescriptor();
    fileDescriptor.setContentType(file.getContentType());
    fileDescriptor.setOriginalName(file.getOriginalFilename());
    fileDescriptor.setNewName(file.getName());
    fileDescriptor.setSize(file.getSize());
    Map<String, Object> result = srv.execute(fileDescriptor, file.getInputStream(), paramValues);

    this.finishRequest();
    result.put("success", true);
    ObjectMapper mapper = getJsonMapper();
    return mapper.writeValueAsString(result);
}

From source file:org.wso2.security.tools.am.webapp.service.DynamicScannerService.java

private MultipartRequestHandler sendRequestToStartScan(String accessToken, DynamicScanner dynamicScanner,
        MultipartFile urlListFile, boolean productUploadAsZip, MultipartFile zipFile, String wso2ServerHost,
        int wso2ServerPort, String scanType) throws URISyntaxException, IOException {
    URI uri = (new URIBuilder()).setHost(GlobalProperties.getAutomationManagerHost())
            .setPort(GlobalProperties.getAutomationManagerPort()).setScheme("https")
            .setPath(GlobalProperties.getDynamicScannerStartScan()).build();
    String charset = "UTF-8";
    MultipartRequestHandler multipartRequest = new MultipartRequestHandler(uri.toString(), charset,
            accessToken);/*from w  w w  .ja va  2 s.co  m*/
    multipartRequest.addFormField("userId", dynamicScanner.getUserId());
    multipartRequest.addFormField("testName", dynamicScanner.getTestName());
    multipartRequest.addFormField("productName", dynamicScanner.getProductName());
    multipartRequest.addFormField("wumLevel", dynamicScanner.getWumLevel());
    multipartRequest.addFormField("productUploadAsZip", String.valueOf(productUploadAsZip));
    multipartRequest.addFilePart("urlListFile", urlListFile.getInputStream(),
            urlListFile.getOriginalFilename());
    multipartRequest.addFormField("scanType", scanType);
    if (productUploadAsZip) {
        multipartRequest.addFilePart("zipFile", zipFile.getInputStream(), zipFile.getOriginalFilename());
    } else {
        multipartRequest.addFormField("wso2ServerHost", wso2ServerHost);
        multipartRequest.addFormField("wso2ServerPort", String.valueOf(wso2ServerPort));
    }
    multipartRequest.finish();
    LOGGER.info("SERVER REPLIED:");
    return multipartRequest;
}

From source file:org.jahia.modules.newsletter.service.SubscriptionService.java

/**
 * Import the subscriber data from the specified CSV file and creates
 * subscriptions for the provided subscribable node.
 *
 * @param subscribableIdentifier the UUID of the target subscribable node
 * @param subscribersCSVFile     the subscribers file in CSV format
 * @param session//from   w w  w .  j  a  va 2 s .c o m
 */
public void importSubscriptions(String subscribableIdentifier, MultipartFile subscribersCSVFile,
        JCRSessionWrapper session, char separator) {
    long timer = System.currentTimeMillis();

    if (logger.isDebugEnabled()) {
        logger.debug("Start importing subscriptions for source node {}", subscribableIdentifier);
    }

    int importedCount = 0;

    InputStream is = null;
    CSVReader reader = null;
    try {
        is = new BufferedInputStream(subscribersCSVFile.getInputStream());
        reader = new CSVReader(new InputStreamReader(is, "UTF-8"), separator);
        String[] columns = reader.readNext();
        int usernamePosition = ArrayUtils.indexOf(columns, "j:nodename");
        int emailPosition = ArrayUtils.indexOf(columns, J_EMAIL);
        if (usernamePosition == -1 && emailPosition == -1) {
            logger.warn("No data for importing subscriptions is found" + " or the file is not well-formed");
            return;
        }
        Map<String, Map<String, Object>> subscribers = new HashMap<String, Map<String, Object>>();
        String[] nextLine;
        while ((nextLine = reader.readNext()) != null) {
            String userKey = usernamePosition != -1 ? nextLine[usernamePosition] : null;
            String email = emailPosition != -1 ? nextLine[emailPosition] : null;
            boolean registered = true;
            if (StringUtils.isNotEmpty(userKey)) {
                // registered Jahia user is provided
                JCRUserNode user = userKey.charAt(0) == '/' ? userManagerService.lookupUserByPath(userKey)
                        : userManagerService.lookupUser(userKey);
                if (user != null) {
                    userKey = user.getPath();
                } else {
                    logger.warn("No user can be found for the specified username '" + userKey
                            + "'. Skipping subscription: " + StringUtils.join(nextLine, separator));
                    continue;
                }
            } else if (StringUtils.isNotEmpty(email)) {
                userKey = email;
                registered = false;
            } else {
                logger.warn("Neither a j:nodename nor j:email is provided." + "Skipping subscription: "
                        + StringUtils.join(nextLine, separator));
                continue;
            }
            Map<String, Object> props = new HashMap<String, Object>(columns.length);
            for (int i = 0; i < columns.length; i++) {
                String column = columns[i];
                if ("j:nodename".equals(column) || !registered && J_EMAIL.equals(column)) {
                    continue;
                }
                props.put(column, nextLine[i]);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Subscribing '" + userKey + "' with properties: " + props);
            }

            subscribers.put(userKey, props);
            if (subscribers.size() > 1000) {
                // flush
                subscribe(subscribableIdentifier, subscribers, session);
                importedCount += subscribers.size();
                subscribers = new HashMap<String, Map<String, Object>>();
            }
        }
        if (!subscribers.isEmpty()) {
            // subscribe the rest
            importedCount += subscribers.size();
            subscribe(subscribableIdentifier, subscribers, session);
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception e) {
                // ignore
            }
        }
        IOUtils.closeQuietly(is);
    }

    if (logger.isInfoEnabled()) {
        logger.info("Importing {} subscriptions for source node {} took {} ms",
                new Object[] { importedCount, subscribableIdentifier, System.currentTimeMillis() - timer });
    }
}

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

/**
 *
 *//*from ww  w  . j av  a  2 s .c  om*/
@RequestMapping(value = "/v1/object/{pid}", method = RequestMethod.POST)
public ModelAndView create(MultipartHttpServletRequest fileRequest, HttpServletResponse response)
        throws InvalidSystemMetadata, InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique,
        UnsupportedType, InsufficientResources, NotImplemented, InvalidRequest {

    Session session = new Session();
    Identifier identifier = new Identifier();
    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");
    }
    identifier.setValue(systemMetadata.getIdentifier().getValue());
    InputStream objectInputStream = null;
    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");
    }
    DateTime dt = new DateTime();
    systemMetadata.setDateUploaded(dt.toDate());
    systemMetadata.setDateSysMetadataModified(dt.toDate());
    if (!this.logRequest(fileRequest, Event.CREATE, identifier)) {

        throw new ServiceFailure("20001", "unable to log request");
    }
    identifier = mnStorage.create(session, identifier, objectInputStream, systemMetadata);

    return new ModelAndView("xmlIdentifierViewResolver", "org.dataone.service.types.v1.Identifier", identifier);
}

From source file:org.wso2.security.tools.am.webapp.service.StaticScannerService.java

private MultipartRequestHandler sendRequestToStartScan(String accessToken, StaticScanner staticScanner,
        boolean sourceCodeUploadAsZip, MultipartFile zipFile, String gitUrl, String scanType)
        throws URISyntaxException, IOException {
    URI uri = (new URIBuilder()).setHost(GlobalProperties.getAutomationManagerHost())
            .setPort(GlobalProperties.getAutomationManagerPort()).setScheme("https")
            .setPath(GlobalProperties.getStaticScannerStartScan()).build();
    String charset = "UTF-8";
    MultipartRequestHandler multipartRequest = new MultipartRequestHandler(uri.toString(), charset,
            accessToken);// ww  w .j  a  va  2s. c  o m
    multipartRequest.addFormField("userId", staticScanner.getUserId());
    multipartRequest.addFormField("testName", staticScanner.getTestName());
    multipartRequest.addFormField("productName", staticScanner.getProductName());
    multipartRequest.addFormField("wumLevel", staticScanner.getWumLevel());
    multipartRequest.addFormField("sourceCodeUploadAsZip", String.valueOf(sourceCodeUploadAsZip));
    multipartRequest.addFormField("scanType", scanType);
    if (sourceCodeUploadAsZip) {
        multipartRequest.addFilePart("zipFile", zipFile.getInputStream(), zipFile.getOriginalFilename());
    } else {
        multipartRequest.addFormField("gitUrl", gitUrl);
    }
    LOGGER.info("SERVER REPLIED:");
    return multipartRequest;
}