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

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

Introduction

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

Prototype

public List  parseRequest(HttpServletRequest request) throws FileUploadException 

Source Link

Document

Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a> compliant <code>multipart/form-data</code> stream.

Usage

From source file:mml.handler.post.MMLPostHandler.java

/**
 * Parse the import params from the request
 * @param request the http request//w  w w .  j  a v a 2 s . c om
 */
void parseImportParams(HttpServletRequest request) throws MMLException {
    try {
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Parse the request
        List items = upload.parseRequest(request);
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                if (fieldName != null) {
                    String contents = item.getString(this.encoding);
                    if (fieldName.equals(Params.DOCID)) {
                        int index = contents.lastIndexOf(".");
                        if (index != -1)
                            contents = contents.substring(0, index);
                        docid = contents;
                    } else if (fieldName.equals(Params.AUTHOR))
                        this.author = contents;
                    else if (fieldName.equals(Params.TITLE))
                        this.title = contents;
                    else if (fieldName.equals(Params.STYLE))
                        this.style = contents;
                    else if (fieldName.equals(Params.FORMAT))
                        this.format = contents;
                    else if (fieldName.equals(Params.SECTION))
                        this.section = contents;
                    else if (fieldName.equals(Params.VERSION1))
                        this.version1 = contents;
                    else if (fieldName.equals(Params.ENCODING))
                        encoding = contents;
                    else if (fieldName.equals(Params.ANNOTATIONS))
                        annotations = (JSONArray) JSONValue.parse(contents);
                }
            } else if (item.getName().length() > 0) {
                try {
                    // item.getName retrieves the ORIGINAL file name
                    String type = item.getContentType();
                    if (type != null) {
                        if (type.startsWith("image/")) {
                            InputStream is = item.getInputStream();
                            ByteHolder bh = new ByteHolder();
                            while (is.available() > 0) {
                                byte[] b = new byte[is.available()];
                                is.read(b);
                                bh.append(b);
                            }
                            ImageFile iFile = new ImageFile(item.getName(), item.getContentType(),
                                    bh.getData());
                            if (images == null)
                                images = new ArrayList<ImageFile>();
                            images.add(iFile);
                        } else if (type.equals("text/plain")) {
                            InputStream is = item.getInputStream();
                            ByteHolder bh = new ByteHolder();
                            while (is.available() > 0) {
                                byte[] b = new byte[is.available()];
                                is.read(b);
                                bh.append(b);
                            }
                            String style = new String(bh.getData(), encoding);
                            if (files == null)
                                files = new ArrayList<String>();
                            files.add(style);
                        }
                    }
                } catch (Exception e) {
                    throw new MMLException(e);
                }
            }
        }
    } catch (Exception e) {
        throw new MMLException(e);
    }
}

From source file:adminpackage.adminview.ProductAddition.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, Exception {
    response.setContentType("text/plain;charset=UTF-8");

    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    AdminViewProduct product = new AdminViewProduct();
    List<FileItem> items = upload.parseRequest(request);
    Iterator itr = items.iterator();
    String value = "defa";
    String url = "";
    while (itr.hasNext()) {
        FileItem item = (FileItem) itr.next();
        if (item.isFormField()) {
            String name = item.getFieldName();
            value = item.getString();//from w  ww .  jav a 2 s  .  c  om
            switch (name) {
            case "pname":
                product.setName(value);
                break;
            case "quantity":
                product.setQuantity(Integer.parseInt(value));
                break;
            case "author":
                product.setAuthor(value);
                break;
            case "isbn":
                product.setISBN(Long.parseLong(value));
                break;
            case "description":
                product.setDescription(value);
                break;
            case "category":
                product.setCategory(value);
                break;
            case "price":
                product.setPrice(Integer.parseInt(value));
                break;
            }
        } else {

            //System.out.println(context.getRealPath("/pages/images/").replaceAll("\\\\target\\\\MavenOnlineShoping-1.0-SNAPSHOT", "\\\\src\\\\main\\\\webapp") + item.getName());
            //url = context.getRealPath("/pages/images/").replaceAll("\\\\target\\\\MavenOnlineShoping-1.0-SNAPSHOT", "\\\\src\\\\main\\\\webapp") + item.getName();
            UUID idOne = UUID.randomUUID();
            product.setImage(idOne.toString() + item.getName().substring(item.getName().length() - 4));
            item.write(new File(context.getRealPath("/pages/images/")
                    .replaceAll("\\\\target\\\\MavenOnlineShoping-1.0-SNAPSHOT", "\\\\src\\\\main\\\\webapp")
                    + idOne.toString() + item.getName().substring(item.getName().length() - 4)));
        }
    }

    PrintWriter out = response.getWriter();

    if (adminFacadeHandler.addBook(product)) {
        out.print("true");
    } else {
        //out.println("false");
        out.print("false");
    }
}

From source file:com.br.ifpb.servlet.UploadImagemPerfil.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*ww  w .  j a  v 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 {
    Usuario usuario = ((Usuario) request.getSession().getAttribute("usuario"));
    if (usuario == null) {
        response.sendRedirect("");
    } else {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = null;
            try {
                items = (List<FileItem>) upload.parseRequest(request);
            } catch (FileUploadException ex) {
                Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
            }
            FileItem item = items.get(0);
            if (item != null) {
                String nome_arquivo = String.valueOf(new Date().getTime()) + item.getName();
                String caminho = getServletContext().getRealPath("/imagens") + "\\" + usuario.getId() + "\\";
                File file = new File(caminho);
                if (!file.exists()) {
                    file.mkdirs();
                }
                File uploadedFile = new File(caminho + nome_arquivo);
                try {
                    item.write(uploadedFile);
                } catch (Exception ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                GerenciarUsuario gerenciarUsuario = new GerenciarUsuario();
                try {
                    gerenciarUsuario.atualizarFotoPerfil("imagens" + "/" + usuario.getId() + "/" + nome_arquivo,
                            usuario.getId());
                } catch (PersistenciaException ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                GerenciarFotos gerenciarFotos = new GerenciarFotos();
                try {
                    gerenciarFotos.publicarFoto("imagens" + "/" + usuario.getId() + "/" + nome_arquivo,
                            Timestamp.valueOf(LocalDateTime.now()), usuario);
                } catch (PersistenciaException ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                try {
                    usuario = gerenciarUsuario.getUsuario(usuario.getId());
                } catch (PersistenciaException ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                request.getSession().setAttribute("usuario", usuario);
                response.sendRedirect("configuracao");
            } else {

            }
        }

    }
}

From source file:cdc.util.Upload.java

public boolean anexos(HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (ServletFileUpload.isMultipartContent(request)) {
        int cont = 0;
        ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
        List fileItemsList = null;
        try {/*w ww.  j a v  a 2  s  .c o  m*/
            fileItemsList = servletFileUpload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        String optionalFileName = "";
        FileItem fileItem = null;
        Iterator it = fileItemsList.iterator();
        do {
            //cont++;
            FileItem fileItemTemp = (FileItem) it.next();
            if (fileItemTemp.isFormField()) {
                if (fileItemTemp.getFieldName().equals("file")) {
                    optionalFileName = fileItemTemp.getString();
                }
            } else {
                fileItem = fileItemTemp;
            }
            if (cont != (fileItemsList.size())) {
                if (fileItem != null) {
                    String fileName = fileItem.getName();
                    if (fileItem.getSize() > 0) {
                        if (optionalFileName.trim().equals("")) {
                            fileName = FilenameUtils.getName(fileName);
                        } else {
                            fileName = optionalFileName;
                        }
                        String dirName = request.getServletContext().getRealPath(pasta);
                        File saveTo = new File(dirName + fileName);
                        //System.out.println("caminho: " + saveTo.toString() );
                        try {
                            fileItem.write(saveTo);
                        } catch (Exception e) {
                        }
                    }
                }
            }
            cont++;
        } while (it.hasNext());
        return true;
    } else {
        return false;
    }
}

From source file:com.sielpe.controller.GestionarCandidatos.java

/**
 * peticion crear nuevo candidato//from  w  w  w.  ja  va 2 s.  c  o  m
 *
 * @param request
 * @param response
 * @throws IOException
 * @throws MiExcepcion
 * @throws ServletException
 */
public void guardarFoto(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    if (request.getParameter("saveImage") != null) {
        String respuesta = "";
        String id = request.getParameter("saveImage");
        byte[] bytes = null;
        try {
            //procesando foto
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload sfu = new ServletFileUpload(factory);
            List items = sfu.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    bytes = item.get();
                }
            }
            respuesta = facadeDAO.fotoCandidato(bytes, id);
        } catch (FileUploadException ex) {
            respuesta = ex.getMessage();
        }
        response.sendRedirect("GestionarCandidatos?msg=" + respuesta);
    } else {
        redirectEditarCandidato(request, response);
    }
}

From source file:com.afspq.web.ProcessQuery.java

@SuppressWarnings({ "unused", "rawtypes" })
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {//  ww  w  . j a  v  a  2  s. c o  m
            String root = getServletContext().getRealPath("/");
            File path = new File(root + "/uploads");
            List items = upload.parseRequest(request);

            if (!path.exists()) {
                boolean status = path.mkdirs();
            }

            if (items.size() > 0) {
                DiskFileItem file = (DiskFileItem) items.get(0);
                File uploadedFile = new File(path + "/" + file.getName());

                file.write(uploadedFile);
                request.setAttribute("results",
                        new ImageResults().getResults(uploadedFile, imageSearch, 0, true));
                request.getRequestDispatcher("imageResults.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.intranet.intr.proyecto.EmpControllerProyectoGaleriaCertificaciones.java

@RequestMapping(value = "ECertificaciones_galeria.htm", method = RequestMethod.POST)
public String fotoEmpleado_post(@ModelAttribute("fotogaleria") proyecto_certificaciones_galeria galer,
        BindingResult result, HttpServletRequest request) {
    String mensaje = "";
    //C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\
    String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\fotosCertificaciones";
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024);// ww w  .jav  a 2  s.com

    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        List<FileItem> partes = upload.parseRequest(request);
        for (FileItem item : partes) {
            galer.setId_proyecto_certificaciones(idPC);
            if (proyectoCertificacionesGaleriaService.existe(item.getName()) == false) {
                System.out.println("NOMBRE FOTO: " + item.getName());
                File file = new File(ubicacionArchivo, item.getName());
                item.write(file);
                galer.setNombreimg(item.getName());
                proyectoCertificacionesGaleriaService.insertar(galer);
            }

        }
        System.out.println("Archi subido correctamente");
    } catch (Exception ex) {
        System.out.println("Error al subir archivo" + ex.getMessage());
    }

    //return "redirect:uploadFile.htm";

    return "redirect:ECertificaciones_galeria.htm?idC=" + idPC.getId();

}

From source file:com.origami.sgm.services.ejbs.censocat.FotosServlet.java

protected void postWithNumId(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    FotoUploadRespMod respModel = new FotoUploadRespMod(false, null);
    try {//from www .j a v  a  2  s.c o  m
        response.setContentType("application/json;charset=UTF-8");
        this.genFactory();
        Long id = Long.parseLong(request.getParameter("id"));
        uploadFotoBean.setPredioId(id);
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        ServletFileUpload upload = new ServletFileUpload(uploadFotoBean.getFactory());
        upload.setFileSizeMax(10000000); // max 10MB
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (item.isFormField()) {
            } else {
                InputStream is = item.getInputStream();
                Long fileId = omegaUploader.uploadFile(is, item.getName(), item.getContentType());
                uploadFotoBean.setFileId(fileId);
                uploadFotoBean.setNombre(item.getName());
                uploadFotoBean.setContentType(item.getContentType());
                uploadFotoBean.saveFotoId();
                respModel.setFotoId(uploadFotoBean.getFotoPredioId());
                respModel.setOk(true);
                is.close();
                break;
            }
        }
    } catch (FileUploadException ex) {
        Logger.getLogger(FotosServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NumberFormatException | IOException ex) {
        Logger.getLogger(FotosServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    ObjectMapper mapper = new ObjectMapper();
    String jsonResp = mapper.writeValueAsString(respModel);
    response.getWriter().write(jsonResp);
}

From source file:hd.controller.AddImageToIdeaBookServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w w w.ja  va2s  .  c om*/
 *
 * @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 {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");

    PrintWriter out = response.getWriter();
    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) { //to do

        } else {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;
            try {
                items = upload.parseRequest(request);

            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            Iterator iter = items.iterator();
            Hashtable params = new Hashtable();

            String fileName = null;
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                    params.put(item.getFieldName(), item.getString("UTF-8"));

                } else if (!item.isFormField()) {
                    try {
                        long time = System.currentTimeMillis();
                        String itemName = item.getName();
                        fileName = time + itemName.substring(itemName.lastIndexOf("\\") + 1);

                        String RealPath = getServletContext().getRealPath("/") + "images\\" + fileName;

                        File savedFile = new File(RealPath);
                        item.write(savedFile);

                        String localPath = "D:\\Project\\TestHouseDecor-Merge\\web\\images\\" + fileName;
                        //                            savedFile = new File(localPath);
                        //                            item.write(savedFile);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }

            String ideaBookIdTemp = (String) params.get("txtIdeabookId");
            int ideaBookId = Integer.parseInt(ideaBookIdTemp);
            IdeaBookDAO ideabookDao = new IdeaBookDAO();

            String tilte = (String) params.get("newGalleryName");

            String description = (String) params.get("GalleryDescription");
            String url = "images/" + fileName;

            IdeaBookPhotoDAO photoDAO = new IdeaBookPhotoDAO();
            IdeaBookPhoto ideaBookPhoto = photoDAO.insertIdeaBookPhoto(tilte, description, url, ideaBookId);

            HDSystem system = new HDSystem();
            system.setNotificationIdeaBook(request);
            response.sendRedirect("MyIdeaBookDetailServlet?txtIdeabookId=" + ideaBookId);

        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        out.close();
    }
}

From source file:fr.opensagres.xdocreport.document.web.UploadXDocReportServlet.java

/**
 * Handles all requests (by default).//from  ww w  .j  a v  a 2 s .co  m
 * 
 * @param request HttpServletRequest object containing client request
 * @param response HttpServletResponse object for the response
 */
protected void doUpload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {

        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        try {
            @SuppressWarnings("unchecked")
            List<FileItem> items = upload.parseRequest(request);
            for (Iterator<FileItem> iterator = items.iterator(); iterator.hasNext();) {

                FileItem fileItem = (FileItem) iterator.next();

                if ("uploadfile".equals(fileItem.getFieldName())) {

                    InputStream in = fileItem.getInputStream();
                    try {
                        String reportId = generateReportId(fileItem, request);
                        IXDocReport report = getRegistryForUpload(request).loadReport(in, reportId);

                        // Check if report id exists in global registry
                        getRegistry(request).checkReportId(report.getId());
                        reportLoaded(report, request);
                        doForward(report, request, response);
                        break;
                    } catch (XDocReportException e) {
                        throw new ServletException(e);
                    }
                }
            }
        } catch (FileUploadException e) {
            throw new ServletException(e);
        }

    }
}