Example usage for javax.servlet.http Part getInputStream

List of usage examples for javax.servlet.http Part getInputStream

Introduction

In this page you can find the example usage for javax.servlet.http Part getInputStream.

Prototype

public InputStream getInputStream() throws IOException;

Source Link

Document

Gets the content of this part as an InputStream

Usage

From source file:marketDB.update_db.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String path = "C:\\Users\\Asus X550ZE\\Documents\\NetBeansProjects\\Web App\\web\\img";
    Cookie[] cookies = request.getCookies();
    String access_token = "";
    for (int i = 0; i < cookies.length; i++) {
        if (cookies[i].getName().equals("access_token")) {
            access_token = cookies[i].getValue();
        }/*from   www . ja va2  s . co m*/
    }
    String product_id = request.getParameter("product_id");
    String product_name = request.getParameter("prod_name");
    String desc = request.getParameter("desc_box");
    String price = request.getParameter("price_box");
    Part filePart = request.getPart("imgcatch");
    String fileName = getFileName(filePart);

    InputStream in = filePart.getInputStream();
    byte[] imgByte = readFully(in);
    int status = 0;

    try {
        status = editProduct(access_token, product_id, product_name, desc, price, fileName, imgByte);
        //WEB SERVICE UPDATE PRODUCT
    } catch (IOException_Exception ex) {
        Logger.getLogger(update_db.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ProtocolException_Exception ex) {
        Logger.getLogger(update_db.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException_Exception ex) {
        Logger.getLogger(update_db.class.getName()).log(Level.SEVERE, null, ex);
    }

    JSONObject arrayObj = new JSONObject();
    arrayObj.put("status", status);
    if (status == 1) {
        response.sendRedirect("your_product.jsp");
    } else {
        response.sendRedirect("login.jsp");
    }

}

From source file:com.ge.apm.service.asset.AttachmentFileService.java

public Integer uploadFile(Part file) {
    Integer returnId = 0;//from ww  w  .j  a  v a 2s  .  c om
    try {
        returnId = fileUploaddao.saveUploadFile(file.getInputStream(),
                Integer.valueOf(String.valueOf(file.getSize())), file.getSubmittedFileName());
    } catch (SQLException | IOException ex) {
        WebUtil.addErrorMessage(WebUtil.getMessage("fileTransFail"));
        Logger.getLogger(AttachmentFileService.class.getName()).log(Level.SEVERE, null, ex);
    }
    return returnId;
}

From source file:marketDB.add_db.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String path = "C:\\Users\\Asus X550ZE\\Documents\\NetBeansProjects\\Web App\\web\\img";
    Cookie[] cookies = request.getCookies();
    String access_token = "";
    for (int i = 0; i < cookies.length; i++) {
        if (cookies[i].getName().equals("access_token")) {
            access_token = cookies[i].getValue();
        }/*from   w w w . j  a v a 2  s. com*/
    }

    String product_name = request.getParameter("prod_name");
    String desc = request.getParameter("desc_box");
    String price = request.getParameter("price_box");
    Part filePart = request.getPart("imgcatch");
    String fileName = getFileName(filePart);

    InputStream in = filePart.getInputStream();
    byte[] imgByte = readFully(in);
    int status = 0;

    try {
        status = addProduct(access_token, product_name, desc, price, fileName, imgByte);
    } catch (ProtocolException_Exception ex) {
        Logger.getLogger(add_db.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException_Exception ex) {
        Logger.getLogger(add_db.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException_Exception ex) {
        Logger.getLogger(add_db.class.getName()).log(Level.SEVERE, null, ex);
    }
    if (status == 1) {
        //WEB SERVICE ADD PRODUCT
        JSONObject arrayObj = new JSONObject();
        //arrayObj.put("status",status);
        //response.setContentType("application/json:charset=UTF-8");
        //response.getWriter().write(arrayObj.toString());
        response.sendRedirect("your_product.jsp");
    } else {
        response.sendRedirect("login.jsp");
    }
}

From source file:com.shoylpik.controller.AddProduct.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String SAVE_DIRECTORY = "shoylpik_images";
    String absolutePath = request.getServletContext().getRealPath("");
    String savePath = absolutePath + File.separator + SAVE_DIRECTORY;

    File imageSaveDirectory = new File(savePath);
    if (!imageSaveDirectory.exists()) {
        imageSaveDirectory.mkdir();//from w w w .  j a v a  2  s.c o m
    }

    System.out.println("imageSaveDirectory.getAbsolutePath(): " + imageSaveDirectory.getAbsolutePath());
    String fileName = null;
    //Get all the parts from request and write it to the file on server
    for (Part part : request.getParts()) {
        fileName = getFileName(part);
        System.out.println("fileName: " + fileName);
        part.write(savePath + File.separator + fileName);
    }

    try {
        System.out.println("savePath : " + savePath);
        String imageName = request.getParameter("IPimage");
        System.out.println("imageName: " + imageName);
        Part filePart = request.getPart("IPimage");
        InputStream imageInputStream = filePart.getInputStream();

        Product product = new Product();
        product.setProductId(Integer.parseInt(request.getParameter("IPID")));
        product.setProductName(request.getParameter("IPname"));
        product.setProductImageName(imageName);
        product.setProductCategory(request.getParameter("IPcat"));
        product.setProductPrice(Float.parseFloat(request.getParameter("IPprice")));
        product.setProductQuantity(Integer.parseInt(request.getParameter("IPQuant")));

        ProductBean pBean = new ProductBean();
        pBean.addProduct(product);

        String fullImagePath = savePath + File.separator + imageName;
        File file = new File(fullImagePath);
        System.out.println("fullImagePath : " + fullImagePath);
        FileOutputStream fos = new FileOutputStream(file);

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) {

        } else {
            System.out.println("Inside else");
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;

            try {
                items = upload.parseRequest(request);
            } catch (FileUploadException e) {

            }
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                System.out.println("Inside while");
                FileItem item = (FileItem) items.iterator();
                item.write(file);
            }
        }
    } catch (SQLException ex) {
        Logger.getLogger(AddProduct.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(AddProduct.class.getName()).log(Level.SEVERE, null, ex);
    }
    response.sendRedirect("AdministrationPage.jsp");
}

From source file:com.spring.tutorial.entitites.FileUploader.java

public String upload() throws IOException, ServletException, FacebookException {
    OutputStream output = null;/*from   w w  w. j av a2  s. co  m*/
    InputStream fileContent = null;
    final Part filePart;

    final File file;
    try {
        filePart = request.getPart("file");

        fileContent = filePart.getInputStream();

        MongoClient mongoClient = new MongoClient();
        mongoClient = new MongoClient();
        DB db = mongoClient.getDB("fou");

        char[] pass = "mongo".toCharArray();
        boolean auth = db.authenticate("admin", pass);

        file = File.createTempFile("fileToStore", "tmp");

        file.deleteOnExit();
        FileOutputStream fout = new FileOutputStream(file);

        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = fileContent.read(bytes)) != -1) {
            fout.write(bytes, 0, read);
        }

        GridFS gridFS = new GridFS(db, request.getSession().getAttribute("id") + "_files");
        GridFSInputFile gfsInputFile = gridFS.createFile(file);
        gfsInputFile.setFilename(filePart.getSubmittedFileName());
        gfsInputFile.save();

        DBCollection collection = db.getCollection(request.getSession().getAttribute("id") + "_files_meta");
        BasicDBObject metaDocument = new BasicDBObject();
        metaDocument.append("name", filePart.getSubmittedFileName());
        metaDocument.append("size", filePart.getSize());
        metaDocument.append("content-type", filePart.getContentType());
        metaDocument.append("file-id", gfsInputFile.getId());
        metaDocument.append("tags", request.getParameter("tags"));
        metaDocument.append("description", request.getParameter("description"));

        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

        metaDocument.append("last_modified", dateFormat.format(new Date()));

        collection.insert(metaDocument);

    } catch (Exception e) {
        return "message:" + e.getMessage();
    } finally {
        if (output != null) {
            output.close();
        }
        if (fileContent != null) {
            fileContent.close();
        }
    }

    return "success";
}

From source file:com.mycompany.osgiwebfelix.MainServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from  ww  w.j a va2  s  . co m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
    String filename = getFilename(filePart);
    InputStream filecontent = filePart.getInputStream();

    BundleDirectoryManager bundleDirMgmt = (BundleDirectoryManager) getServletContext()
            .getAttribute("bundleDirMgmt");
    BundleInstaller bi = new BundleInstaller(getServletContext());
    try {
        bi.installBundleFromFile(bundleDirMgmt.saveBundleStreamToFile(filename, filecontent), true, false);
    } catch (BundleException ex) {
        Logger.getLogger(MainServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.sishuok.chapter4.web.servlet.UploadServlet.java

@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    try {//from ww  w .j  a v a 2 s. co  m

        //servlet?Partnull
        //9.0.4.v20130625 ??
        System.out.println(req.getParameter("name"));

        //?Part
        System.out.println("\n\n==========file1");
        Part file1Part = req.getPart("file1"); //?? ?Part
        InputStream file1PartInputStream = file1Part.getInputStream();
        System.out.println(IOUtils.toString(file1PartInputStream));
        file1PartInputStream.close();

        // ??
        System.out.println("\n\n==========file2");
        Part file2Part = req.getPart("file2");
        InputStream file2PartInputStream = file2Part.getInputStream();
        System.out.println(IOUtils.toString(file2PartInputStream));
        file2PartInputStream.close();

        System.out.println("\n\n==========parameter name");
        //????
        System.out.println(IOUtils.toString(req.getPart("name").getInputStream()));
        //Part??? jettyparameters??
        System.out.println(req.getParameter("name"));

        //?? ? req.getInputStream(); ??

        System.out.println("\n\n=============all part");
        for (Part part : req.getParts()) {
            System.out.println("\n\n=========name:::" + part.getName());
            System.out.println("=========size:::" + part.getSize());
            System.out.println("=========content-type:::" + part.getContentType());
            System.out
                    .println("=========header content-disposition:::" + part.getHeader("content-disposition"));
            System.out.println("=========file name:::" + getFileName(part));
            InputStream partInputStream = part.getInputStream();
            System.out.println("=========value:::" + IOUtils.toString(partInputStream));

            //
            partInputStream.close();
            // ? ? ?
            part.delete();

        }

    } catch (IllegalStateException ise) {
        //
        ise.printStackTrace();
        String errorMsg = ise.getMessage();
        if (errorMsg.contains("Request exceeds maxRequestSize")) {
            //?
        } else if (errorMsg.contains("Multipart Mime part file1 exceeds max filesize")) {
            //? ??
        } else {
            //
        }
    }

}

From source file:cheladocs.controlo.DocumentoServlet.java

private void doUpload(Part part, HttpServletRequest request) {
    try {/*www .j a v a 2s .com*/

        InputStream in = part.getInputStream();

        File f = new File("c:\\ficheiros_docs\\" + part.getSubmittedFileName());

        f.createNewFile();
        FileOutputStream out = new FileOutputStream(f);

        byte[] buffer = new byte[1024 * 1024 * 100];

        int length;

        while ((length = in.read(buffer)) > 0) {
            out.write(buffer, 0, length);
        }
        out.close();
        in.close();

    } catch (IOException ex) {
        ex.printStackTrace(System.out);
    }
}

From source file:org.cirdles.webServices.ambapo.AmbapoServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request// ww w  . j a v a2 s  .c  o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/csv");
    response.setHeader("Content-Disposition", "attachment; filename=converted-file.csv");

    String conversionType = ServletRequestUtils.getStringParameter(request, "conversionType", "LatLongtoUTM");
    Part filePart = request.getPart("ambapoFile");

    String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
    InputStream fileStream = filePart.getInputStream();
    File myFile = new File(fileName);

    AmbapoFileHandlerService handler = new AmbapoFileHandlerService();
    String fileExt = FilenameUtils.getExtension(fileName);

    try {
        File convertedFile = null;
        if (fileExt.equals("csv")) {
            convertedFile = handler.convertFile(fileName, fileStream, conversionType).toFile();
            response.setContentLengthLong(convertedFile.length());
            IOUtils.copy(new FileInputStream(convertedFile), response.getOutputStream());
        }

        else {
        }

    } catch (Exception e) {
        System.err.println(e);
    }

}

From source file:net.myrrix.web.servlets.IngestServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    MyrrixRecommender recommender = getRecommender();

    boolean fromBrowserUpload = request.getContentType().startsWith("multipart/form-data");

    Reader reader;//from   w w w.  j  av  a 2s.c o  m
    if (fromBrowserUpload) {

        Collection<Part> parts = request.getParts();
        if (parts == null || parts.isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No form data");
            return;
        }
        Part part = parts.iterator().next();
        String partContentType = part.getContentType();
        InputStream in = part.getInputStream();
        if ("application/zip".equals(partContentType)) {
            in = new ZipInputStream(in);
        } else if ("application/gzip".equals(partContentType)) {
            in = new GZIPInputStream(in);
        } else if ("application/x-gzip".equals(partContentType)) {
            in = new GZIPInputStream(in);
        } else if ("application/bzip2".equals(partContentType)) {
            in = new BZip2CompressorInputStream(in);
        } else if ("application/x-bzip2".equals(partContentType)) {
            in = new BZip2CompressorInputStream(in);
        }
        reader = new InputStreamReader(in, Charsets.UTF_8);

    } else {

        String charEncodingName = request.getCharacterEncoding();
        Charset charEncoding = charEncodingName == null ? Charsets.UTF_8 : Charset.forName(charEncodingName);
        String contentEncoding = request.getHeader(HttpHeaders.CONTENT_ENCODING);
        if (contentEncoding == null) {
            reader = request.getReader();
        } else if ("gzip".equals(contentEncoding)) {
            reader = new InputStreamReader(new GZIPInputStream(request.getInputStream()), charEncoding);
        } else if ("zip".equals(contentEncoding)) {
            reader = new InputStreamReader(new ZipInputStream(request.getInputStream()), charEncoding);
        } else if ("bzip2".equals(contentEncoding)) {
            reader = new InputStreamReader(new BZip2CompressorInputStream(request.getInputStream()),
                    charEncoding);
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unsupported Content-Encoding");
            return;
        }

    }

    try {
        recommender.ingest(reader);
    } catch (IllegalArgumentException iae) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.toString());
        return;
    } catch (NoSuchElementException nsee) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString());
        return;
    } catch (TasteException te) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, te.toString());
        getServletContext().log("Unexpected error in " + getClass().getSimpleName(), te);
        return;
    }

    String referer = request.getHeader(HttpHeaders.REFERER);
    if (fromBrowserUpload && referer != null) {
        // Parsing avoids response splitting
        response.sendRedirect(new URL(referer).toString());
    }

}