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:lk.studysmart.apps.BrainTeaserFileUpload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w w w .ja v  a  2  s  . c  o  m
 *
 * @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");

    user = (User) request.getSession().getAttribute("user");
    //Get information from tha frontend of file upload
    final Part filePart = request.getPart("file");
    final String fileName = request.getParameter("filename");
    final String description = request.getParameter("description");

    InputStream filecontent = filePart.getInputStream();

    byte[] bytes = IOUtils.readFully(filecontent, Integer.valueOf(Long.toString(filePart.getSize())));

    Subject subject = em.find(Subject.class, request.getParameter("subject"));

    //Set attribute values to object 
    Internalresources resource = new Internalresources();
    resource.setUser(user);
    resource.setSubject(subject);
    resource.setFilename(fileName);
    resource.setDescription(description);
    resource.setBlob(bytes);

    try {
        utx.begin();
        em.persist(resource);
        utx.commit();
    } catch (NotSupportedException | SystemException | RollbackException | HeuristicMixedException
            | HeuristicRollbackException | SecurityException | IllegalStateException ex) {
        Logger.getLogger(BrainTeaserFileUpload.class.getName()).log(Level.SEVERE, null, ex);
        response.getWriter().write("Error: " + ex.getLocalizedMessage());
    }
    //Redirect page to the teacher's VLE main interface
    response.sendRedirect("teachVLEMUI.jsp?msg=File Uploaded");
}

From source file:Package.Projectoverviewservlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    frame.setAlwaysOnTop(true);//ww w.  j  a  v a 2s  . c om
    if (request.getParameter("submit") != null) {
        Database database = null;
        try {
            database = new Database();
            database.Connect();
        } catch (SQLException | ClassNotFoundException ex) {
            Logger.getLogger(Projectoverviewservlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            String contentType = request.getContentType();
            if ((contentType.indexOf("multipart/form-data") >= 0)) {
                try {
                    Part filePart = request.getPart("fileupload");
                    Image image = ImageIO.read(filePart.getInputStream());
                    String INSERT_PICTURE = "INSERT INTO \"PICTURE\"(\"PICTUREID\", \"PROJECTID\", \"HEIGHT\", \"WIDTH\", \"COLORTYPE\", \"PICTURE\") VALUES (PictureSequence.nextval, 1,"
                            + image.getHeight(null) + "," + image.getWidth(null) + ", 'Color', ?)";
                    InputStream is = null;
                    PreparedStatement ps = null;
                    try {
                        is = filePart.getInputStream();
                        ps = database.myConn.prepareStatement(INSERT_PICTURE);
                        ps.setBlob(1, is);
                        ps.executeUpdate();
                        database.myConn.commit();
                        JOptionPane.showMessageDialog(frame, "De afbeelding is succesvol geupload.");
                    } finally {
                        try {
                            ps.close();
                            is.close();
                        } catch (Exception exception) {

                        }
                    }
                } catch (IOException | ServletException | SQLException ex) {
                    System.out.println(ex);
                }
            } else {
                JOptionPane.showMessageDialog(frame, "Er is iets fout gegaan probeer het opnieuw");
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(frame, ex.getMessage());
        }
        response.sendRedirect("projectoverview.jsp");
    }

    if (request.getParameter("deleteproject") != null) {
        String[] selectresults = request.getParameterValues("selectproject");
        po.deleteProject(Integer.parseInt(selectresults[0]));

    }

    if (request.getParameter("openproject") != null) {
        try {
            String[] selectresults = request.getParameterValues("selectproject");
            Project project = po.getProject(Integer.parseInt(selectresults[0]));
            request.setAttribute("project", project);
            request.getRequestDispatcher("projectoverview.jsp").forward(request, response);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(frame, ex.getMessage());
        }

    }

    if (request.getParameter("Save") != null) {

        Project project = (Project) request.getAttribute("project");
        if (project != null) {
            try {
                System.out.println(request.getParameter("startdate"));
                po.updateProject(project.getProjectID(), request.getParameter("name"),
                        request.getParameter("client"),
                        new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("startdate")),
                        new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("enddate")));
            } catch (Exception ex) {

            }
        } else {
            String username = "";
            for (Cookie cookie : request.getCookies()) {
                if (cookie.getName().equals("Email")) {
                    username = cookie.getValue();
                }
            }
            if (!username.isEmpty()) {
                try {
                    po.createProject(po.connection.getCompanyID(username), request.getParameter("name"),
                            request.getParameter("client"),
                            new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("startdate")),
                            new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("enddate")));
                } catch (ParseException ex) {
                    Logger.getLogger(Projectoverviewservlet.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            //roep create aan
        }
        request.getRequestDispatcher("projectoverview.jsp").forward(request, response);
    }

    if (request.getParameter("deleteimage") != null) {

    }

    if (request.getParameter("importimage") != null) {

    }

    if (request.getParameter("koppel") != null) {

    }

    if (request.getParameter("addemail") != null) {

    }

    if (request.getParameter("deleteemail") != null) {

    }

    if (request.getParameter("importemail") != null) {

    }

}

From source file:AddPost.java

private String getPostString() throws IOException, ServletException {
    String textPost = "";
    Collection<Part> p = mReq.getParts();
    for (Part part : p) {
        if (part.getName().equals("post")) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), "UTF-8"));
            StringBuilder value = new StringBuilder();
            char[] buffer = new char[1024];
            for (int length = 0; (length = reader.read(buffer)) > 0;) {
                value.append(buffer, 0, length);
            }/*from  www  .ja v a 2 s  .  c  o m*/
            textPost = value.toString();
        }
    }
    return textPost;
}

From source file:net.bluemix.droneselfie.UploadPictureServlet.java

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

    String id = request.getParameter("id");
    if (id == null)
        return;/*from w  ww . ja v  a  2  s  .  c  om*/
    if (id.equals(""))
        return;

    InputStream inputStream = null;
    Part filePart = request.getPart("my_file");
    if (filePart != null) {
        inputStream = filePart.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        org.apache.commons.io.IOUtils.copy(inputStream, baos);
        byte[] bytes = baos.toByteArray();
        ByteArrayInputStream bistream = new ByteArrayInputStream(bytes);
        String contentType = "image/png";

        java.util.Date date = new java.util.Date();
        String uniqueId = String.valueOf(date.getTime());
        AttachmentDoc document = new AttachmentDoc(id, AttachmentDoc.TYPE_FULL_PICTURE, date);
        DatabaseUtilities.getSingleton().getDB().create(document.getId(), document);
        document = DatabaseUtilities.getSingleton().getDB().get(AttachmentDoc.class, id);
        AttachmentInputStream ais = new AttachmentInputStream(id, bistream, contentType);
        DatabaseUtilities.getSingleton().getDB().createAttachment(id, document.getRevision(), ais);

        javax.websocket.Session ssession;
        ssession = net.bluemix.droneselfie.SocketEndpoint.currentSession;
        if (ssession != null) {
            for (Session session : ssession.getOpenSessions()) {
                try {
                    if (session.isOpen()) {
                        session.getBasicRemote().sendText("fpic?id=" + id);
                    }
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }

        String alchemyUrl = "";
        String apiKey = ConfigUtilities.getSingleton().getAlchemyAPIKey();
        String bluemixAppName = ConfigUtilities.getSingleton().getBluemixAppName();

        /*
        if (bluemixAppName == null) {
           String host = request.getServerName();
           alchemyUrl = "http://access.alchemyapi.com/calls/url/URLGetRankedImageFaceTags?url=http://" + host +"/pic?id="
          + id + "&apikey=" + apiKey + "&outputMode=json";
        }
        else {
           alchemyUrl = "http://access.alchemyapi.com/calls/url/URLGetRankedImageFaceTags?url=http://" + bluemixAppName +".mybluemix.net/pic?id="
          + id + "&apikey=" + apiKey + "&outputMode=json";
        }*/

        alchemyUrl = "http://access.alchemyapi.com/calls/url/URLGetRankedImageFaceTags?url=http://ar-drone-selfie.mybluemix.net/pic?id="
                + id + "&apikey=1657f33d25d39ff6d226c5547db6190ea8d5af76&outputMode=json";
        System.out.println("alchemyURL: " + alchemyUrl);
        org.apache.http.client.fluent.Request req = Request.Post(alchemyUrl);
        org.apache.http.client.fluent.Response res = req.execute();

        String output = res.returnContent().asString();
        Gson gson = new Gson();

        AlchemyResponse alchemyResponse = gson.fromJson(output, AlchemyResponse.class);

        if (alchemyResponse != null) {
            List<ImageFace> faces = alchemyResponse.getImageFaces();
            if (faces != null) {
                for (int i = 0; i < faces.size(); i++) {
                    ImageFace face = faces.get(i);
                    String sH = face.getHeight();
                    String sPX = face.getPositionX();
                    String sPY = face.getPositionY();
                    String sW = face.getWidth();
                    int height = Integer.parseInt(sH);
                    int positionX = Integer.parseInt(sPX);
                    int positionY = Integer.parseInt(sPY);
                    int width = Integer.parseInt(sW);

                    int fullPictureWidth = 640;
                    int fullPictureHeight = 360;
                    positionX = positionX - width / 2;
                    positionY = positionY - height / 2;
                    height = height * 2;
                    width = width * 2;
                    if (positionX < 0)
                        positionX = 0;
                    if (positionY < 0)
                        positionY = 0;
                    if (positionX + width > fullPictureWidth)
                        width = width - (fullPictureWidth - positionX);
                    if (positionY + height > fullPictureHeight)
                        height = height - (fullPictureHeight - positionY);

                    bistream = new ByteArrayInputStream(bytes);
                    javaxt.io.Image image = new javaxt.io.Image(bistream);
                    image.crop(positionX, positionY, width, height);
                    byte[] croppedImage = image.getByteArray();

                    ByteArrayInputStream bis = new ByteArrayInputStream(croppedImage);

                    date = new java.util.Date();
                    uniqueId = String.valueOf(date.getTime());
                    document = new AttachmentDoc(uniqueId, AttachmentDoc.TYPE_PORTRAIT, date);
                    DatabaseUtilities.getSingleton().getDB().create(document.getId(), document);
                    document = DatabaseUtilities.getSingleton().getDB().get(AttachmentDoc.class, uniqueId);

                    ais = new AttachmentInputStream(uniqueId, bis, contentType);
                    DatabaseUtilities.getSingleton().getDB().createAttachment(uniqueId, document.getRevision(),
                            ais);

                    ssession = net.bluemix.droneselfie.SocketEndpoint.currentSession;
                    if (ssession != null) {
                        for (Session session : ssession.getOpenSessions()) {
                            try {
                                if (session.isOpen()) {
                                    /*
                                     * In addition to portrait url why don't we send a few meta back to client
                                     */
                                    ImageTag tag = face.getImageTag();
                                    tag.setUrl("pic?id=" + uniqueId);
                                    session.getBasicRemote().sendText(tag.toString());
                                }
                            } catch (IOException ioe) {
                                ioe.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:org.clothocad.phagebook.controllers.PersonController.java

private static String getValue(Part part) throws IOException {
    System.out.println("Reached get Value");
    BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), "UTF-8"));
    StringBuilder value = new StringBuilder();
    char[] buffer = new char[1024];
    for (int length = 0; (length = reader.read(buffer)) > 0;) {
        System.out.print(".");
        value.append(buffer, 0, length);
    }/*w w  w .jav a 2  s . co m*/
    System.out.println("Value :: " + value.toString());
    return value.toString();
}

From source file:it.unitn.elisco.servlet.ImageUploadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* w w w .ja 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 {

    HttpSession session = request.getSession(false);
    Person user;

    if (request.getRequestURI().equals("/admin/image_upload")) {
        user = (Person) session.getAttribute("admin");
    } else {
        user = (Person) session.getAttribute("student");
    }
    // Get the image uploaded by the user as a stream
    Part imagePart = request.getPart("image");
    String imageExtension = "." + imagePart.getSubmittedFileName().split("\\.")[1];

    // Write to a temp file
    File tempFile = File.createTempFile("tmp", imageExtension);
    tempFile.deleteOnExit();
    FileOutputStream out = new FileOutputStream(tempFile);
    IOUtils.copy(imagePart.getInputStream(), out);

    // Upload the image to Cloudinary
    ImageUploader uploader = ImageUploader.getInstance();
    String imageId = uploader.uploadImageToCloud(user, tempFile);

    // Get the url for the uploaded image
    String imageUrl = uploader.getURLWithDimensions(imageId, 200, 200);

    // Send JSON response back to ajax
    String json = new Gson().toJson(imageUrl);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

From source file:cheladocs.controlo.DocumentoServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("application/pdf; application/msword; application/excel");

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

    if (comando == null) {
        comando = "principal";
    }// w  w w.  j a  v  a2  s.  c  om

    DocumentoDAO documentoDAO;
    Documento documento = new Documento();

    if (comando == null || !comando.equalsIgnoreCase("principal")) {
        try {
            idDocumento = request.getParameter("numero_protocolo");
            if (idDocumento != null) {
                documento.setNumeroProtocolo(Integer.parseInt(idDocumento));
            }

        } catch (NumberFormatException ex) {
            System.err.println("Erro ao converter dado: " + ex.getMessage());
        }
    }

    try {

        documentoDAO = new DocumentoDAO();

        if (comando.equalsIgnoreCase("guardar")) {

            documento.getRequerente().setIdRequerente(Integer.parseInt(request.getParameter("requerente")));
            documento.setDataEntrada(Date.valueOf(request.getParameter("data_entrada")));
            documento.setOrigem(request.getParameter("origem_documento"));
            documento.setDescricaoAssunto(request.getParameter("descricao_assunto"));
            documento.getNaturezaAssunto()
                    .setIdNaturezaAssunto(Integer.parseInt(request.getParameter("natureza_assunto")));
            documento.getTipoExpediente()
                    .setIdTipoExpediente(Integer.parseInt(request.getParameter("tipo_expediente")));
            Part ficheiro = request.getPart("ficheiro");
            if (ficheiro != null) {
                byte[] ficheiroDados = IOUtils.toByteArray(ficheiro.getInputStream());
                documento.setConteudoDocumento(ficheiroDados);
                documento.setUrlFicheiroDocumento(ficheiro.getSubmittedFileName());
                doUpload(ficheiro, request);
            }
            documentoDAO.save(documento);
            response.sendRedirect("paginas/gerir_documento.jsp");

        } else if (comando.equalsIgnoreCase("editar")) {

            documento.setNumeroProtocolo(Integer.parseInt(request.getParameter("requerente")));

            documento.getRequerente().setIdRequerente(Integer.parseInt(request.getParameter("requerente")));
            documento.setDataEntrada(Date.valueOf(request.getParameter("data_entrada")));
            documento.setOrigem(request.getParameter("origem_documento"));
            documento.setDescricaoAssunto(request.getParameter("descricao_assunto"));
            documento.getNaturezaAssunto()
                    .setIdNaturezaAssunto(Integer.parseInt(request.getParameter("natureza_assunto")));
            documento.getTipoExpediente()
                    .setIdTipoExpediente(Integer.parseInt(request.getParameter("tipo_expediente")));
            Part ficheiro = request.getPart("ficheiro");
            if (ficheiro != null) {
                byte[] ficheiroDados = IOUtils.toByteArray(ficheiro.getInputStream());
                documento.setConteudoDocumento(ficheiroDados);
                documento.setUrlFicheiroDocumento(ficheiro.getSubmittedFileName());
                doUpload(ficheiro, request);
            }

            documentoDAO.update(documento);
            response.sendRedirect("paginas/gerir_documento.jsp");

        } else if (comando.equalsIgnoreCase("eliminar")) {
            documentoDAO.delete(documento);
            response.sendRedirect("paginas/gerir_documento.jsp");

        } else if (comando.equalsIgnoreCase("prepara_editar")) {
            documento = documentoDAO.findById(documento.getNumeroProtocolo());
            request.setAttribute("documento", documento);

            RequestDispatcher rd = request.getRequestDispatcher("paginas/documento_editar.jsp");
            rd.forward(request, response);
        } else if (comando.equalsIgnoreCase("listar")) {

            response.sendRedirect("paginas/gerir_documento.jsp");
        } else if (comando.equalsIgnoreCase("imprimir_todos") || comando.equalsIgnoreCase("imprimir_by_id")) {
            ReporteUtil reporte = new ReporteUtil();
            File caminhoRelatorio = null;
            HashMap hashMap = new HashMap();

            if (comando.equalsIgnoreCase("imprimir_todos")) {
                caminhoRelatorio = new File(getServletConfig().getServletContext()
                        .getRealPath("/WEB-INF/relatorios/DocumentoListar.jasper"));
                reporte.geraRelatorio(caminhoRelatorio.getPath(), hashMap, response);
            } else {
                hashMap.put("codigo_documento", Integer.parseInt(idDocumento));
                caminhoRelatorio = new File(getServletConfig().getServletContext()
                        .getRealPath("/WEB-INF/relatorios/Ficha_Documento.jasper"));
                reporte.geraRelatorio(caminhoRelatorio.getPath(), hashMap, response);
            }
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.curso.ejemplohinputfile.FileUploadBean.java

public String processFileUpload() throws IOException {
    Part uploadedFile = getFile();
    final Path destination = Paths.get("c:/tmp/" + FilenameUtils.getName(getSubmittedFileName(uploadedFile)));
    //Con servlet 3.1
    //final Path destination = Paths.get("c:/tmp/"+ FilenameUtils.getName(uploadedFile.getSubmittedFileName()));
    InputStream bytes = null;//from www  .j  a  v  a 2s  .c om
    if (null != uploadedFile) {
        bytes = uploadedFile.getInputStream(); //
        Files.copy(bytes, destination);
    }
    return "success";
}

From source file:org.apache.sling.servlets.post.impl.operations.StreamedUploadOperation.java

/**
 * Add a field to the store of formFields.
 * @param formFields the formFileds/*from   www  . j a  v a2 s  .c  o m*/
 * @param name the name of the field.
 * @param part the part.
 */
private void addField(Map<String, List<String>> formFields, String name, Part part) {
    List<String> values = formFields.get(name);
    if (values == null) {
        values = new ArrayList<String>();
        formFields.put(name, values);
    }
    try {
        values.add(IOUtils.toString(part.getInputStream(), "UTF-8"));
    } catch (IOException e) {
        LOG.error("Failed to read form field " + name, e);
    }
}

From source file:com.thoughtworks.go.apiv1.configrepooperations.ConfigRepoOperationsControllerV1.java

String preflight(Request req, Response res) throws IOException {
    ConfigRepoConfig repo = repoFromRequest(req);
    ConfigRepoPlugin plugin = pluginFromRequest(req);
    PartialConfigLoadContext context = configContext(repo);

    final PreflightResult result = new PreflightResult();

    try {/*from   w w w.  j  a v a2 s .  com*/
        Collection<Part> uploads = req.raw().getParts();
        Map<String, String> contents = new LinkedHashMap<>();

        for (Part ul : uploads) {
            if (!"files[]".equals(ul.getName())) {
                continue;
            }

            StringWriter w = new StringWriter();
            IOUtils.copy(ul.getInputStream(), w, StandardCharsets.UTF_8);
            contents.put(ul.getSubmittedFileName(), w.toString());
        }

        if (contents.isEmpty()) {
            result.update(Collections.singletonList(
                    "No file content provided; check to make sure you POST the form data as `files[]=`"),
                    false);
        } else {
            PartialConfig partialConfig = plugin.parseContent(contents, context);
            partialConfig.setOrigins(adHocConfigOrigin(repo));
            CruiseConfig config = partialConfigService.merge(partialConfig,
                    context.configMaterial().getFingerprint(), gcs.clonedConfigForEdit());

            gcs.validateCruiseConfig(config);
            result.update(Collections.emptyList(), true);
        }
    } catch (RecordNotFoundException e) {
        throw e;
    } catch (InvalidPartialConfigException e) {
        result.update(Collections.singletonList(e.getErrors()), false);
    } catch (GoConfigInvalidException e) {
        result.update(e.getAllErrors(), false);
    } catch (Exception e) {
        throw HaltApiResponses.haltBecauseOfReason(e.getMessage());
    }

    return writerForTopLevelObject(req, res, w -> PreflightResultRepresenter.toJSON(w, result));
}