Example usage for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent.

Prototype

public static final boolean isMultipartContent(HttpServletRequest request) 

Source Link

Document

Utility method that determines whether the request contains multipart content.

Usage

From source file:FileUploading.UploadServlet.java

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

    //check that we have a file upload request 
    isMultipart = ServletFileUpload.isMultipartContent(req);

    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();
    if (!isMultipart) {

        String title = "";
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("<body>");
        out.println("<body>");
        out.println("<p> No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;// www . j ava2  s.co m
    }

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in the memory
    factory.setSizeThreshold(maxMemSize);
    // location to save data that is larger than maxMemsize
    factory.setRepository(new File("C:\\temp"));

    //create a new file upload handler 
    ServletFileUpload upload = new ServletFileUpload(factory);
    //maximum file size to be upload 
    upload.setSizeMax(maxFileSize);
    try {
        //parse the requset to get file items 
        List fileItems = upload.parseRequest(req);
        // process the uploaded file items
        Iterator i = fileItems.iterator();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servket Upload</title>");
        out.println("</head>");
        out.println("<body>");
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                //get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInMemory = fi.getSize();

                //write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }
                fi.write(file);
                out.println("Uploaded file name : " + fileName + "<br>");
            }
        }
        out.println("</body>");
        out.println("</html>");
    } catch (Exception e) {
    }
}

From source file:control.UploadFile.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {/*  w w  w. j  a  va2  s .com*/
        boolean ismultipart = ServletFileUpload.isMultipartContent(request);
        if (!ismultipart) {
        } else {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            List items = null;
            System.out.println(request);
            try {
                items = upload.parseRequest(request);
            } catch (Exception e) {

            }
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {

                } else {
                    String itemname = item.getName();
                    if (itemname == null || itemname.equals("")) {
                        continue;
                    }
                    String filename = FilenameUtils.getName(itemname);
                    File f = checkExist(filename);
                    item.write(f);
                    request.getRequestDispatcher("/ideaCreated.jsp").forward(request, response);
                }
            }
        }
    } catch (Exception e) {
    } finally {
        out.close();
    }
}

From source file:com.mycompany.memegenerator.FileUpload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  www. j  a v  a2  s  .  co  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 {
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();
                    byte[] byteImage = item.get();
                    uploadImage = ImageIO.read(new ByteArrayInputStream(byteImage));
                    //ImageIO.write(uploadImage, "jpg", new File("C:\\uploads","snap.jpg"));

                    // get session
                    HttpSession session = request.getSession();
                    session.setAttribute("byteImage", byteImage);
                    session.setAttribute("uploadImage", uploadImage);

                }
            }

            //File uploaded successfully
            request.setAttribute("message", "File Uploaded Successfully");
        } catch (Exception ex) {
            request.setAttribute("message", "File Upload Failed due to " + ex);
        }

    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }

    request.getRequestDispatcher("/index.jsp").forward(request, response);

}

From source file:AES.Controllers.FileController.java

@RequestMapping(value = "/upload", method = RequestMethod.GET)
public void upload(HttpServletResponse response, HttpServletRequest request,
        @RequestParam Map<String, String> requestParams) throws IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("Hello<br/>");

    boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
    if (!isMultipartContent) {
        out.println("You are not trying to upload<br/>");
        return;/*from  w  ww  .  j  a v  a2s  . c o m*/
    }
    out.println("You are trying to upload<br/>");

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        List<FileItem> fields = upload.parseRequest(request);
        out.println("Number of fields: " + fields.size() + "<br/><br/>");
        Iterator<FileItem> it = fields.iterator();
        if (!it.hasNext()) {
            out.println("No fields found");
            return;
        }
        out.println("<table border=\"1\">");
        while (it.hasNext()) {
            out.println("<tr>");
            FileItem fileItem = it.next();
            boolean isFormField = fileItem.isFormField();
            if (isFormField) {
                out.println("<td>regular form field</td><td>FIELD NAME: " + fileItem.getFieldName()
                        + "<br/>STRING: " + fileItem.getString());
                out.println("</td>");
            } else {
                out.println("<td>file form field</td><td>FIELD NAME: " + fileItem.getFieldName()
                        + "<br/>STRING: " + fileItem.getString() + "<br/>NAME: " + fileItem.getName()
                        + "<br/>CONTENT TYPE: " + fileItem.getContentType() + "<br/>SIZE (BYTES): "
                        + fileItem.getSize() + "<br/>TO STRING: " + fileItem.toString());
                out.println("</td>");
                String path = request.getSession().getServletContext().getRealPath("") + "\\uploads\\";
                //System.out.println(request.getSession().getServletContext().getRealPath(""));
                File f = new File(path + fileItem.getName());
                if (!f.exists())
                    f.createNewFile();
                fileItem.write(f);
            }
            out.println("</tr>");
        }
        out.println("</table>");
    } catch (FileUploadException e) {
        e.printStackTrace();
    } catch (Exception ex) {
        Logger.getLogger(FileController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.redoute.datamap.servlet.picture.AddPicture.java

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

    String page = "";
    String application = "";
    String pictureName = "";
    String screenshot = "";
    FileItem item = null;/*from   w  w w.j a  v  a 2  s .c  om*/

    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {

            String fileName = null;
            List items = upload.parseRequest(request);
            List items2 = items;
            Iterator iterator = items.iterator();
            Iterator iterator2 = items2.iterator();
            File uploadedFile = null;
            String idNC = "";

            while (iterator.hasNext()) {
                item = (FileItem) iterator.next();

                if (item.isFormField()) {
                    String name = item.getFieldName();
                    if (name.equals("Page")) {
                        page = item.getString("UTF-8");
                        System.out.println(page);
                    }
                    if (name.equals("Application")) {
                        application = item.getString("UTF-8");
                        System.out.println(application);
                    }
                    if (name.equals("PictureName")) {
                        pictureName = item.getString("UTF-8");
                        System.out.println(pictureName);
                    }
                    if (name.equals("Screenshot")) {
                        screenshot = item.getString().split("<img src=\"")[1].split("\">")[0];
                        System.out.println(screenshot);
                        System.out.println(screenshot.length());
                    }
                }
            }

            ApplicationContext appContext = WebApplicationContextUtils
                    .getWebApplicationContext(this.getServletContext());
            IPictureService pictService = appContext.getBean(IPictureService.class);
            IFactoryPicture factoryPicture = appContext.getBean(IFactoryPicture.class);

            Picture pict = factoryPicture.create(0, application, page, pictureName, screenshot);
            pictService.createPicture(pict);

            response.sendRedirect("Datamap.jsp");
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

From source file:controlador.SerPartido.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    //ruta relativa en donde se guardan las imagenes de partidos
    String ruta = getServletContext().getRealPath("/") + "images/files/banderas/";//imagenes de los partidos politicos
    Partido p = new Partido();
    int accion = 1; //1=gregar  2=modificar
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        diskFileItemFactory.setSizeThreshold(40960);
        File repositoryPath = new File("/temp");
        diskFileItemFactory.setRepository(repositoryPath);
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        servletFileUpload.setSizeMax(81920); // bytes
        upload.setSizeMax(307200); // 1024 x 300 = 307200 bytes = 300 Kb
        List listUploadFiles = null;
        FileItem item = null;// www . j  a v a2 s  . c o  m
        try {
            listUploadFiles = upload.parseRequest(request);
            Iterator it = listUploadFiles.iterator();
            while (it.hasNext()) {
                item = (FileItem) it.next();
                if (!item.isFormField()) {
                    if (item.getSize() > 0) {
                        String nombre = item.getName();
                        String tipo = item.getContentType();
                        long tamanio = item.getSize();
                        String extension = nombre.substring(nombre.lastIndexOf("."));
                        File archivo = new File(ruta, nombre);
                        item.write(archivo);
                        if (archivo.exists()) {
                            p.setImagen(nombre);
                        } else {
                            out.println("FALLO AL GUARDAR. NO EXISTE " + archivo.getAbsolutePath() + "</p>");
                        }
                    }
                } else {
                    //se reciben los campos de texto enviados y se igualan a los atributos del objeto
                    if (item.getFieldName().equals("txtAcronimo")) {
                        p.setAcronimo(item.getString());
                    }
                    if (item.getFieldName().equals("txtNombre")) {
                        p.setNombre(item.getString());
                    }
                    if (item.getFieldName().equals("txtDui")) {
                        p.setNumDui(item.getString());
                    }
                    if (item.getFieldName().equals("txtId")) {
                        p.setIdPartido(Integer.parseInt(item.getString()));
                    }

                }
            }
            //si no se selecciono una imagen distinta, se conserva la imagen anterior
            if (p.getImagen() == null) {
                p.setImagen(PartidoDTO.mostrarPartido(p.getIdPartido()).getImagen());
            }

            //cuando se presiona el boton de agregar
            if (p.getIdPartido() == 0) {
                if (PartidoDTO.agregarPartido(p)) {
                    response.sendRedirect(this.redireccionJSP);
                } else {
                    //cambiar por alguna accion en caso de error
                    out.print("Error al insertar");
                }
            }
            //cuando se presiona el boton de modificar
            else {
                if (PartidoDTO.modificarPartido(p)) {
                    response.sendRedirect(this.redireccionJSP);
                } else {
                    out.print("Error al modificar");
                }
            }

        } catch (FileUploadException e) {
            out.println("Error Upload: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            out.println("Error otros: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

From source file:importer.handler.post.HTMLImportHandler.java

public void handle(HttpServletRequest request, HttpServletResponse response, String urn)
        throws ImporterException {
    try {//  w  ww. j  a  v a 2 s  . c om
        if (ServletFileUpload.isMultipartContent(request)) {
            parseImportParams(request);
            Archive cortex = new Archive(getWork(), getAuthor(), Formats.TEXT, encoding);
            Archive corcode = new Archive(getWork(), getAuthor(), Formats.STIL, encoding);
            cortex.setStyle(style);
            corcode.setStyle(style);
            StageOne stage1 = new StageOne(files);
            log.append(stage1.process(cortex, corcode));
            if (stage1.hasFiles()) {
                String suffix = "";
                StageTwo stage2 = new StageTwo(stage1, false);
                stage2.setEncoding(encoding);
                log.append(stage2.process(cortex, corcode));
                Stage3HTML stage3Html = new Stage3HTML(stage2, style, dict, hhExceptions, encoding);
                if (stripperName == null || stripperName.equals("default"))
                    stripperName = "html";
                stage3Html.setStripConfig(getConfig(Config.stripper, stripperName));
                log.append(stage3Html.process(cortex, corcode));
                addToDBase(cortex, "cortex", suffix);
                addToDBase(corcode, "corcode", suffix);
            }
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().println(wrapLog());
        }
    } catch (Exception e) {
        throw new ImporterException(e);
    }
}

From source file:adminShop.registraProducto.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w w w . ja v  a  2s .  co 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 {
    String message = "Error";
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items;
        HashMap hm = new HashMap();
        ArrayList<Imagen> imgs = new ArrayList<>();
        Producto prod = new Producto();
        Imagen img = null;
        try {
            items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    String value = item.getString();
                    hm.put(name, value);
                } else {
                    img = new Imagen();
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeBytes = item.getSize();
                    File file = new File("/home/gama/Escritorio/adoo/" + fileName + ".jpg");
                    item.write(file);
                    Path path = Paths.get("/home/gama/Escritorio/adoo/" + fileName + ".jpg");
                    byte[] data = Files.readAllBytes(path);
                    byte[] encode = org.apache.commons.codec.binary.Base64.encodeBase64(data);
                    img.setUrl(new javax.sql.rowset.serial.SerialBlob(encode));
                    imgs.add(img);
                    //file.delete();
                }
            }
            prod.setNombre((String) hm.get("nombre"));
            prod.setProdNum((String) hm.get("prodNum"));
            prod.setDesc((String) hm.get("desc"));
            prod.setIva(Double.parseDouble((String) hm.get("iva")));
            prod.setPrecio(Double.parseDouble((String) hm.get("precio")));
            prod.setPiezas(Integer.parseInt((String) hm.get("piezas")));
            prod.setEstatus("A");
            prod.setImagenes(imgs);
            ProductoDAO prodDAO = new ProductoDAO();
            if (prodDAO.registraProducto(prod)) {
                message = "Exito";
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    response.sendRedirect("index.jsp");
}

From source file:controller.uploadPergunta3.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  w  w .  j av 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 {

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

    String name = "";
    //process only if its multipart content
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    name = new File(item.getName()).getName();
                    //                        item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
                    item.write(new File(AbsolutePath + File.separator + name));
                }
            }

            //File uploaded successfully
            request.setAttribute("message", "File Uploaded Successfully");
        } catch (Exception ex) {
            request.setAttribute("message", "File Upload Failed due to " + ex);
        }

    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }

    //        request.getRequestDispatcher("/novoLocalPergunta3?id="+idLocal+"&fupload=1&nomeArquivo="+name).forward(request, response);
    //        String x = "/novoLocalPergunta3.jsp?id="+idLocal+"&nomeArquivo="+name;
    //        request.getRequestDispatcher(x).forward(request, response);

    RequestDispatcher view = getServletContext()
            .getRequestDispatcher("/novoLocalPergunta3?id=" + idLocal + "&nomeArquivo=" + name);
    view.forward(request, response);

}

From source file:com.kunal.NewServlet2.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from ww w. j a va 2s .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 {
    if (ServletFileUpload.isMultipartContent(request)) {

        try {
            HttpSession session = request.getSession();
            String V_Str_Id = (String) session.getAttribute("VSID");
            String containerName = V_Str_Id;
            //String fileName = "Ad2";
            String userId = "7f7a82c6a2464a45b0ea5b7c65c90f38";
            String password = "lM_EC#0a7U})SE-.";
            String auth_url = "https://lon-identity.open.softlayer.com" + "/v3";
            String domain = "1090141";
            String project = "object_storage_e32c650b_e512_4e44_aeb8_c49fdf1de69f";
            Identifier domainIdent = Identifier.byName(domain);
            Identifier projectIdent = Identifier.byName(project);

            OSClient os = OSFactory.builderV3().endpoint(auth_url).credentials(userId, password)
                    .scopeToProject(projectIdent, domainIdent).authenticate();

            SwiftAccount account = os.objectStorage().account().get();
            ObjectStorageService objectStorage = os.objectStorage();
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();
                    System.out.println(name);
                    // item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
                    String etag = os.objectStorage().objects().put(containerName, name,
                            Payloads.create(item.getInputStream()));
                    System.out.println(etag);
                }
            }

            //File uploaded successfully
            request.setAttribute("message", "File Uploaded Successfully");
        } catch (Exception ex) {
            request.setAttribute("message", "File Upload Failed due to " + ex);
        }

    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }

    request.getRequestDispatcher("/Pre_Installation.jsp").forward(request, response);

}