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:org.sonar.server.ws.ServletRequest.java

@Override
protected InputStream readInputStreamParam(String key) {
    Part part = readPart(key);
    return (part == null) ? null : part.getInputStream();
}

From source file:cn.mypandora.controller.MyUpload.java

/**
 * ?????/*from  w  w w  .java 2  s.  c  o  m*/
 *
 * @param part
 */
@RequestMapping(value = "import", method = RequestMethod.POST)
public void importUser(@RequestParam("myFile") Part part) {
    try {
        InputStream inputStream = part.getInputStream();
        String fileName = getFileName(part);
        String fieldNames = "08,??, , ??, ?, , ?, , ";
        List<Map<String, String>> listmap = MyExcelUtil.readExcelToMap(inputStream, fileName, fieldNames);
        for (Map<String, String> foo : listmap) {
            while (foo.entrySet().iterator().hasNext()) {
                System.out.println(123);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.ibm.bluemix.hack.image.ImageEvaluator.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)//from  ww  w  .  ja  va  2 s.co  m
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Part file = request.getPart("image_file");
    InputStream is = file.getInputStream();
    byte[] buf = IOUtils.toByteArray(is);
    JSONObject results = analyzeImage(buf);

    request.setAttribute("results", results);

    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/image.jsp");
    dispatcher.forward(request, response);

}

From source file:controllers.IndexServlet.java

private static void Upload(HttpServletRequest request, HttpServletResponse response, PrintWriter writer) {
    response.setContentType("text/plain");

    try {/* www . java 2s. com*/
        Part httpPostedFile = request.getPart("file");

        String fileName = "";
        for (String content : httpPostedFile.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                fileName = content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }

        long curSize = httpPostedFile.getSize();
        if (DocumentManager.GetMaxFileSize() < curSize || curSize <= 0) {
            writer.write("{ \"error\": \"File size is incorrect\"}");
            return;
        }

        String curExt = FileUtility.GetFileExtension(fileName);
        if (!DocumentManager.GetFileExts().contains(curExt)) {
            writer.write("{ \"error\": \"File type is not supported\"}");
            return;
        }

        InputStream fileStream = httpPostedFile.getInputStream();

        fileName = DocumentManager.GetCorrectName(fileName);
        String fileStoragePath = DocumentManager.StoragePath(fileName, null);

        File file = new File(fileStoragePath);

        try (FileOutputStream out = new FileOutputStream(file)) {
            int read;
            final byte[] bytes = new byte[1024];
            while ((read = fileStream.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }

            out.flush();
        }

        writer.write("{ \"filename\": \"" + fileName + "\"}");

    } catch (IOException | ServletException e) {
        writer.write("{ \"error\": \"" + e.getMessage() + "\"}");
    }
}

From source file:org.beta.reiszeimage.ImageUploadServlet.java

private File extractParts(HttpServletRequest request) {
    try {//from ww w.  j  ava2 s. c  om
        final File fl = new File(outputDirectory);
        if (!fl.exists()) {
            fl.createNewFile();
        }
        final Part part = request.getPart("img");
        final InputStream input = part.getInputStream();

        byte[] buffer = new byte[1024];
        int noOfBytes = 0;
        final FileOutputStream fos = new FileOutputStream(fl);
        while ((noOfBytes = input.read(buffer)) != -1) {
            fos.write(buffer, 0, noOfBytes);
        }
        fos.flush();
        fos.close();
        return fl;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:es.uma.inftel.blog.servlet.RegistroServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/* w  w w .  j a  v a  2 s . c  o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8");

    String username = request.getParameter("username");
    String password = request.getParameter("password");

    RegistroViewFacade registroViewFacade = new RegistroViewFacade(postFacade);

    RequestDispatcher registroRequestDispatcher = request.getRequestDispatcher("registro.jsp");
    if (username == null && password == null) {
        request.setAttribute("registroView", registroViewFacade.createView(false));
        registroRequestDispatcher.forward(request, response);
        return;
    }

    String email = request.getParameter("email");

    Part filePart = request.getPart("avatar");
    InputStream inputStream = filePart.getInputStream();
    byte[] avatar = IOUtils.toByteArray(inputStream);

    Usuario usuario = registrarUsuario(username, password, email, avatar);
    if (usuario == null) {
        request.setAttribute("registroView", registroViewFacade.createView(true));
        registroRequestDispatcher.forward(request, response);
    } else {
        HttpSession session = request.getSession();
        session.setAttribute("usuario", usuario);
        response.sendRedirect("index");
    }
}

From source file:com.levalo.contacts.view.ContactView.java

public void importContactFromXml(ValueChangeEvent event) {
    try {//from   w w w .  ja  v  a 2 s.  c  om
        Part uploadedXmlContact = (Part) event.getNewValue();
        StringWriter sw = new StringWriter();
        IOUtils.copy(uploadedXmlContact.getInputStream(), sw);
        this.contact = contactService.getContactFromXml(sw.toString());
    } catch (Exception ex) {
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "Invalid xml file"));
        logger.log(Level.INFO, ex.getMessage());
    }
}

From source file:com.orangeandbronze.jblubble.sample.UploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String pathInfo = request.getPathInfo();
    if (pathInfo == null) {
        pathInfo = "/";
    }//  w w  w . j  a v  a  2  s  . c  o  m
    LOGGER.debug("POST {}{}", PATH, pathInfo);
    Part part = request.getPart("file");
    if (part != null) {
        BlobKey blobKey = blobstoreService.createBlob(part.getInputStream(), getFileName(part),
                part.getContentType());
        LOGGER.debug("Created blob, generated key [{}]", blobKey);
        blobKeys.add(blobKey);
    }
    response.sendRedirect(request.getServletContext().getContextPath() + "/uploads");
}

From source file:com.galenframework.storage.controllers.api.PageApiController.java

private FileInfo copyImageToStorage(Request req) throws IOException, ServletException {
    if (req.raw().getAttribute("org.eclipse.jetty.multipartConfig") == null) {
        MultipartConfigElement multipartConfigElement = new MultipartConfigElement(
                System.getProperty("java.io.tmpdir"));
        req.raw().setAttribute("org.eclipse.jetty.multipartConfig", multipartConfigElement);
    }//  w  w w.  j a  v a  2s. c o  m

    Part file = req.raw().getPart("file");
    FileInfo imageInfo = fileStorage.saveImageToStorage(file.getInputStream());
    file.delete();
    return imageInfo;
}

From source file:VideoTestServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w w w. j a va 2  s . com
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    final Part filePart = request.getPart("file");
    String filename = getFileName(filePart);
    InputStream filecontent = filePart.getInputStream();
    byte[] bytes = new byte[filecontent.available()];
    filecontent.read(bytes);

    /*OutputStream PDFprint = response.getOutputStream();
    PDFprint.write(bytes);
    if(PDFprint != null){
    PDFprint.close();
    }*/

    byte[] encoded = Base64.encodeBase64(bytes);
    String encodedString = new String(encoded);
    System.out.println(encodedString);
    String title = "Video Servlet";
    String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";

    out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n"
            + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n"
            + "<video width=\"320\" hieght=\"240\" controls>"
            + "<source type=\"video/webm\" src=\"data:video/webm;base64," + encodedString + "\">"
            + "Your browser does not support the video element" + "</video>" + "</body></html>");

}