Example usage for javax.servlet.http HttpServletRequest getPart

List of usage examples for javax.servlet.http HttpServletRequest getPart

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getPart.

Prototype

public Part getPart(String name) throws IOException, ServletException;

Source Link

Document

Gets the Part with the given name.

Usage

From source file:controllers.IndexServlet.java

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

    try {/* w w  w .  j av  a 2s  . c  om*/
        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:com.sishuok.chapter4.web.servlet.UploadServlet3.java

@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    Part part = req.getPart("file1");
    InputStream is = part.getInputStream();
    System.out.println(IOUtils.toString(is));
    is.close();/*  ww w .ja  v a2 s.  c  o  m*/

    /**
     * jetty
     * fileSizeThreshold
     * 1?content-disposition???
     * 2??byte array input stream
     * 3?[2]?fileSizeThreshold
     *
     * 4??
     * 4.1?@MultipartConfiglocation?
     * 4.2?Part.write ?
     *
     */

}

From source file:com.viseur.control.UploadImageServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from www  .jav  a2 s  .c  om*/
 * @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 imgPart = request.getPart("imageupload");
    String extension = request.getParameter("extension");
    int maxMB = Integer.valueOf(request.getParameter("maxsize"));

    //   String contextPath = request.getServletContext().getRealPath(""); //Files will be stored inside BUILD folder
    String imgName = UUID.randomUUID().toString();
    String filePath = "/temp/" + imgName + extension;
    String destination = VHost.UPLOAD + filePath;
    FileUpload imgUpload = new FileUpload(extension, maxMB, destination);
    boolean success = imgUpload.NewFileUpload(imgPart);

    JSONObject json = new JSONObject();
    json.put("success", success);
    if (success) {
        json.put("img", imgName);
        json.put("imgUrl", filePath);
    } else {
        json.put("error", imgUpload.error.mMessage);
    }

    try (PrintWriter out = response.getWriter()) {
        out.print(json);
        out.flush();
    }

}

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

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   w  w  w.  j  av  a 2 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.ibm.bluemix.hack.image.ImageEvaluator.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)//from  w  w  w  . j av  a  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:uk.ac.dundee.computing.aec.instagrim.servlets.EditProfile.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  ww  w .  jav  a 2s  .  c om
 * @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 part = request.getPart("upfile");
    System.out.println("Part Name " + part.getName());
    String type = part.getContentType();
    String filename = part.getSubmittedFileName();
    InputStream is = request.getPart(part.getName()).getInputStream();
    int i = is.available();
    HttpSession session = request.getSession();
    LoggedIn lg = (LoggedIn) session.getAttribute("LoggedIn");
    String username = "majed";
    if (lg.getlogedin()) {
        username = lg.getUsername();
    }
    if (i > 0) {
        byte[] b = new byte[i + 1];
        is.read(b);
        System.out.println("Length : " + b.length);
        PicModel tm = new PicModel();
        tm.setCluster(cluster);
        String message = " ";
        java.util.UUID picid = tm.insertPic(b, type, filename, username, message);
        session.setAttribute("picid", picid);
        is.close();
    }

    PrintWriter out = response.getWriter();
    User u = new User();
    u.setCluster(cluster);
    String first_name = (String) request.getParameter("first_name");
    String last_name = (String) request.getParameter("last_name");
    String interest = (String) request.getParameter("interest");
    String email = (String) request.getParameter("email");
    String address = (String) request.getParameter("address");
    out.println(first_name);
    java.util.UUID picid;
    picid = (java.util.UUID) session.getAttribute("picid");
    u.setUserProfile(username, first_name, last_name, interest, email, address, picid);
    java.util.LinkedList<String> userProfile = u.getUserProfile(username);
    session.setAttribute("profile", userProfile);
    RequestDispatcher rd = request.getRequestDispatcher("profile.jsp");
    rd.forward(request, response);
}

From source file:br.edu.ifpb.sislivros.actions.CadastrarLivro.java

private Livro montarLivro(HttpServletRequest request)
        throws FileUploadException, IOException, ServletException {
    Livro livro = new Livro();

    //processando e salvando a capa do livro
    Part capaPart = request.getPart("capa");
    String nomeArquivo = capaPart.getSubmittedFileName();
    if (nomeArquivo == null || nomeArquivo == "")
        nomeArquivo = "img/livros/capa_default.png";
    String isbn = request.getParameter("isbn");
    String capa = new ProcessadorFotos("img/livros").processarArquivoCapa(request, capaPart,
            "capa" + isbn + nomeArquivo);
    livro.setCapa(capa);/*from  w w  w. j  ava  2s  . c  o m*/

    int ano = Integer.parseInt(request.getParameter("anoPublicacao"));
    livro.setAnoPublicacao(ano);
    livro.setAreaTema(request.getParameter("areaTema"));
    livro.setAutores(request.getParameter("autores"));
    livro.setEditora(request.getParameter("editora"));
    livro.setIsbn(isbn);
    livro.setTitulo(request.getParameter("titulo"));

    return livro;
}

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

private File extractParts(HttpServletRequest request) {
    try {/*from   w  ww  .  ja  v a  2s. c o  m*/
        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:CiudadesApp.Modelo.Parameter.GuardarCiudades_Parameter.java

public GuardarCiudades_Parameter(HttpServletRequest request) {

    try {/*ww w  .  j a  v a2  s .  c  om*/
        request.setCharacterEncoding("UTF-8");

        nombreCiudad = (String) request.getParameter("nombreCiudad");
        descripcion = (String) request.getParameter("descripcion");
        Part filePart = request.getPart("fileName");
        InputStream in = filePart.getInputStream();
        foto = IOUtils.toByteArray(in);

    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(GuardarCiudades_Parameter.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GuardarCiudades_Parameter.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ServletException ex) {
        Logger.getLogger(GuardarCiudades_Parameter.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:VideoTestServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  ww . j a  v  a2  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");
    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>");

}