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:com.silverpeas.servlets.upload.AjaxFileUploadServlet.java

/**
 * Do the effective upload of files./*from   ww  w  .ja va2  s.c om*/
 *
 * @param session the HttpSession
 * @param request the multpart request
 * @throws IOException
 */
@SuppressWarnings("unchecked")
private void doFileUpload(HttpSession session, HttpServletRequest request) throws IOException {
    try {
        session.setAttribute(UPLOAD_ERRORS, "");
        session.setAttribute(UPLOAD_FATAL_ERROR, "");
        List<String> paths = new ArrayList<String>();
        session.setAttribute(FILE_UPLOAD_PATHS, paths);
        FileUploadListener listener = new FileUploadListener(request.getContentLength());
        session.setAttribute(FILE_UPLOAD_STATS, listener.getFileUploadStats());
        FileItemFactory factory = new MonitoringFileItemFactory(listener);
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = (List<FileItem>) upload.parseRequest(request);
        startingToSaveUploadedFile(session);
        String errorMessage = "";
        for (FileItem fileItem : items) {
            if (!fileItem.isFormField() && fileItem.getSize() > 0L) {
                try {
                    String filename = fileItem.getName();
                    if (filename.indexOf('/') >= 0) {
                        filename = filename.substring(filename.lastIndexOf('/') + 1);
                    }
                    if (filename.indexOf('\\') >= 0) {
                        filename = filename.substring(filename.lastIndexOf('\\') + 1);
                    }
                    if (!isInWhiteList(filename)) {
                        errorMessage += "The file " + filename + " is not uploaded!";
                        errorMessage += (StringUtil.isDefined(whiteList)
                                ? " Only " + whiteList.replaceAll(" ", ", ")
                                        + " file types can be uploaded<br/>"
                                : " No allowed file format has been defined for upload<br/>");
                        session.setAttribute(UPLOAD_ERRORS, errorMessage);
                    } else {
                        filename = System.currentTimeMillis() + "-" + filename;
                        File targetDirectory = new File(uploadDir, fileItem.getFieldName());
                        targetDirectory.mkdirs();
                        File uploadedFile = new File(targetDirectory, filename);
                        OutputStream out = null;
                        try {
                            out = new FileOutputStream(uploadedFile);
                            IOUtils.copy(fileItem.getInputStream(), out);
                            paths.add(uploadedFile.getParentFile().getName() + '/' + uploadedFile.getName());
                        } finally {
                            IOUtils.closeQuietly(out);
                        }
                    }
                } finally {
                    fileItem.delete();
                }
            }
        }
    } catch (Exception e) {
        Logger.getLogger(getClass().getSimpleName()).log(Level.WARNING, e.getMessage());
        session.setAttribute(UPLOAD_FATAL_ERROR,
                "Could not process uploaded file. Please see log for details.");
    } finally {
        endingToSaveUploadedFile(session);
    }
}

From source file:dk.dma.msinm.web.rest.LocationRestService.java

/**
 * Parse the KML file of the uploaded .kmz or .kml file and returns a JSON list of locations
 *
 * @param request the servlet request//from w w  w  .  j  a v  a  2s . co  m
 * @return the corresponding list of locations
 */
@POST
@javax.ws.rs.Path("/upload-kml")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("application/json;charset=UTF-8")
public List<LocationVo> uploadKml(@Context HttpServletRequest request) throws FileUploadException, IOException {
    FileItemFactory factory = RepositoryService.newDiskFileItemFactory(servletContext);
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = upload.parseRequest(request);

    for (FileItem item : items) {
        if (!item.isFormField()) {
            try {
                // .kml file
                if (item.getName().toLowerCase().endsWith(".kml")) {
                    // Parse the KML and return the corresponding locations
                    return parseKml(IOUtils.toString(item.getInputStream()));
                }

                // .kmz file
                else if (item.getName().toLowerCase().endsWith(".kmz")) {
                    // Parse the .kmz file as a zip file
                    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(item.getInputStream()));
                    ZipEntry entry;

                    // Look for the first zip entry with a .kml extension
                    while ((entry = zis.getNextEntry()) != null) {
                        if (!entry.getName().toLowerCase().endsWith(".kml")) {
                            continue;
                        }

                        log.info("Unzipping: " + entry.getName());
                        int size;
                        byte[] buffer = new byte[2048];
                        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                        while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
                            bytes.write(buffer, 0, size);
                        }
                        bytes.flush();
                        zis.close();

                        // Parse the KML and return the corresponding locations
                        return parseKml(new String(bytes.toByteArray(), "UTF-8"));
                    }
                }

            } catch (Exception ex) {
                log.error("Error extracting kmz", ex);
            }
        }
    }

    // Return an empty result
    return new ArrayList<>();
}

From source file:ned.bcvs.admin.fileupload.VoterFileUploadServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;// w  w  w.  j  a va2  s .c o  m
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File(
            "D:/glassfish12October/glassfish-4.0/glassfish4/" + "glassfish/domains/domain1/applications/temp"));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet 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();
                fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = 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 Filename: " + fileName + "<br>");
                out.println("Uploaded Filepath: " + filePath + fileName + "<br>");
            }
        }
        //calling the ejb method to save voter.csv file to data base
        out.println(upbean.fileDbUploader(filePath + fileName, "voter"));

        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:Control.LoadImage.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*ww w.  j  a  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 {
    String tempPath = "/temp";
    String absoluteTempPath = this.getServletContext().getRealPath(tempPath);
    String absoluteFilePath = this.getServletContext().getRealPath("/data/Image");
    int maxFileSize = 50 * 1024;
    int maxMemSize = 4 * 1024;

    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(maxMemSize);
        File file = new File(absoluteTempPath);

        if (file == null) {
            // tao thu muc
        }

        factory.setRepository(file);
        ServletFileUpload upload = new ServletFileUpload(factory);

        //upload.setProgressListener(new MyProgressListener(out));
        List<FileItem> items = upload.parseRequest(request);

        if (items.size() > 0) {
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    if ("images".equals(item.getFieldName())) {
                        if (item.getName() != null && !item.getName().isEmpty()) {
                            String extension = null;
                            if (item.getName().endsWith("jpg")) {
                                String newLink = "/Image/" + Image.LengthListImg() + ".jpg";
                                file = new File(absoluteFilePath + "//" + Image.LengthListImg() + ".jpg");
                                // G?i hm add hnh vo database, link hnh l newLink
                                item.write(file);
                            } else if (item.getName().endsWith("png")) {
                                String newLink = "/Image/" + Image.LengthListImg() + ".png";
                                file = new File(absoluteFilePath + "//" + Image.LengthListImg() + ".png");
                                // G?i hm add hnh vo database, link hnh l newLink
                                item.write(file);
                            } else if (item.getName().endsWith("JPG")) {
                                String newLink = "/Image/" + Image.LengthListImg() + ".JPG";
                                file = new File(absoluteFilePath + "//" + Image.LengthListImg() + ".JPG");
                                // G?i hm add hnh vo database, link hnh l newLink
                                item.write(file);
                            } else if (item.getName().endsWith("PNG")) {
                                String newLink = "/Image/" + Image.LengthListImg() + ".PNG";
                                file = new File(absoluteFilePath + "//" + Image.LengthListImg() + ".PNG");
                                // G?i hm add hnh vo database, link hnh l newLink
                                item.write(file);
                            }
                        }
                    }
                } else {
                }
            }
            response.sendRedirect(request.getContextPath() + "/LoadImage.jsp");
            return;
        }

        List<Image> images = loadImages(request, response);

        request.setAttribute("images", images);
        request.setAttribute("error", "No file upload");
        RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/LoadImage.jsp");
        dispatcher.forward(request, response);
    } catch (Exception ex) {
        System.err.println(ex);
    }
}

From source file:ca.qc.cegepoutaouais.tge.pige.server.UserImportService.java

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

    hasError = Boolean.FALSE;/*w  w  w.j  a v a  2  s .c om*/
    writer = resp.getWriter();

    logger.info("Rception de la requte HTTP pour l'imporation d'usagers.");

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(SIZE_THRESHOLD);

    ServletFileUpload uploadHandler = new ServletFileUpload(factory);
    try {
        List<FileItem> items = uploadHandler.parseRequest(req);
        if (items.size() == 0) {
            logger.error("Le message ne contient pas de fichier "
                    + "d'importation. Le processus ne pourra donc pas " + "continuer.");
            writer.println("Erreur: Aucun fichier prsent dans le message");
            return;
        }

        Charset cs = null;
        for (FileItem item : items) {
            if (item.getFieldName().equalsIgnoreCase("importFileEncoding-hidden")) {
                String encoding = item.getString();
                if (encoding == null || encoding.isEmpty()) {
                    logger.error("Le message ne contient pas l'encodage utilis "
                            + "dans le fichier d'importation. Le processus ne pourra " + "donc pas continuer.");
                    writer.println("Erreur: Aucun encodage trouv dans les " + "paramtres du message.");
                    return;
                }
                cs = Charset.forName(encoding);
                if (cs == null) {
                    logger.error("L'encodage spcifi n'existe pas (" + encoding + "). "
                            + "Le processus ne pourra donc pas continuer.");
                    writer.println("Erreur: Aucun encodage trouv portant le " + "nom '" + encoding + "'.");
                    return;
                }
            }
        }

        for (FileItem item : items) {
            if (item.getFieldName().equalsIgnoreCase("usersImportFile")) {
                logger.info("Extraction du fichier d'importation  partir " + "du message.");
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(new ByteArrayInputStream(item.get()), cs));
                doUsersImport(reader, req);
                break;
            }
        }

        if (!hasError) {
            logger.info("L'importation des usagers s'est termine avec succs.");
            writer.println("Importation russie!");
        } else {
            logger.info("L'importation des usagers s'est termine avec des erreurs.");
            writer.println("L'importation s'est termine avec des erreurs.");
        }

    } catch (FileUploadException fuex) {
        fuex.printStackTrace();
        logger.error(fuex);
    } catch (Exception ex) {
        ex.printStackTrace();
        logger.error(ex);
    }

}

From source file:edu.lafayette.metadb.web.projectman.CreateProject.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)/*from w  w  w.  j a  va2 s  . c  o  m*/
 */
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    PrintWriter out = response.getWriter();
    JSONObject output = new JSONObject();
    String delimiter = "";
    String projname = "";
    String projnotes = "";
    String template = "";
    boolean useTemplate = false;
    boolean disableQualifier = false;
    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
            List fileItemsList = servletFileUpload.parseRequest(request);
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */

            Iterator it = fileItemsList.iterator();
            InputStream input = null;
            while (it.hasNext()) {
                FileItem fileItem = (FileItem) it.next();
                //MetaDbHelper.note("Field name: "+fileItem.getFieldName());
                //MetaDbHelper.note(fileItem.getString());
                if (fileItem.isFormField()) {
                    /*
                     * The file item contains a simple name-value pair of a
                     * form field
                     */
                    if (fileItem.getFieldName().equals("delimiter") && delimiter.equals(""))
                        delimiter = fileItem.getString();
                    else if (fileItem.getFieldName().equals("projname") && projname.equals(""))
                        projname = fileItem.getString().replace(" ", "_");
                    else if (fileItem.getFieldName().equals("projnotes") && projnotes.equals(""))
                        projnotes = fileItem.getString();
                    else if (fileItem.getFieldName().equals("project-template-checkbox"))
                        useTemplate = true;
                    else if (fileItem.getFieldName().equals("project-template"))
                        template = fileItem.getString().replace(" ", "_");
                    //else if (fileItem.getFieldName().equals("disable-qualifier-checkbox"))
                    //disableQualifier = true;
                } else
                    input = fileItem.getInputStream();

            }
            String userName = Global.METADB_USER;

            HttpSession session = request.getSession(false);
            if (session != null) {
                userName = (String) session.getAttribute(Global.SESSION_USERNAME);
            }

            //MetaDbHelper.note("Delimiter: "+delimiter+", projname: "+projname+", projnotes: "+projnotes+", use template or not? "+useTemplate+" template: "+template);
            if (useTemplate) {
                ProjectsDAO.createProject(template, projname, projnotes, "");
                output.put("projname", projname);
                output.put("success", true);
                output.put("message", "Project created successfully based on: " + template);
                SysLogDAO.log(userName, Global.SYSLOG_PROJECT,
                        "User created project " + projname + " with template from " + template);
            } else {
                if (ProjectsDAO.createProject(projname, projnotes)) {
                    output.put("projname", projname);
                    String delimiterType = "csv";
                    if (delimiter.equals("tab")) {
                        delimiterType = "tsv";
                        disableQualifier = true; // Disable text qualifiers for TSV files.
                    }
                    //MetaDbHelper.note("Delim: "+delimiterType+", projname: "+projname+", input: "+input);
                    if (input != null) {
                        Result res = DataImporter.importFile(delimiterType, projname, input, disableQualifier);
                        output.put("success", res.isSuccess());
                        if (res.isSuccess()) {
                            output.put("message", "Data import successfully");
                            SysLogDAO.log(userName, Global.SYSLOG_PROJECT,
                                    "User created project " + projname + " with file import");
                        } else {

                            output.put("message", "The following fields have been changed");
                            SysLogDAO.log(userName, Global.SYSLOG_PROJECT,
                                    "User created project " + projname + " with file import");
                            String fields = "";
                            ArrayList<String> data = (ArrayList<String>) res.getData();
                            for (String field : data)
                                fields += field + ',';
                            output.put("fields", fields);
                        }
                    } else {
                        output.put("success", true);
                        output.put("message",
                                "Project created successfully with default fields. No data imported");
                        SysLogDAO.log(userName, Global.SYSLOG_PROJECT, "User created project " + projname);
                    }
                } else {
                    output.put("success", false);
                    output.put("message", "Cannot create project");
                    SysLogDAO.log(userName, Global.SYSLOG_PROJECT, "User failed to create project " + projname);
                }
            }
        } else {
            output.put("success", false);
            output.put("message", "Form is not multi-part");
        }
    } catch (NullPointerException e) {
        try {
            output.put("success", true);
            output.put("message", "Project created successfully");
        } catch (JSONException e1) {
            MetaDbHelper.logEvent(e1);
        }

    } catch (Exception e) {
        MetaDbHelper.logEvent(e);
        try {
            output.put("success", false);
            output.put("message", "Project was not created");
        } catch (JSONException e1) {
            MetaDbHelper.logEvent(e1);
        }
    }
    out.print(output);
    out.flush();

}

From source file:com.example.web.UploadServlet.java

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

    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    //response.setContentType("text/html");
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    if (!isMultipart) {

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");

        return;/*from  w ww  . j  a  va 2s  .c  o  m*/
    }

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in 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 uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet 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 sizeInBytes = 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 Filename: " + fileName + "<br>");
            }
        }
        out.println("</body>");
        out.println("</html>");

    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:edu.uniminuto.servlets.GuardarDisco.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*  w ww .  ja va 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
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String nombre = "";
    long precio = 0;
    int anhio = 0;
    short genero = 1;
    int interprete = 1;

    //        String nombre = getParameter(request, "nombre");
    //        long precio = Long.valueOf(getParameter(request, "precio"));
    //        int anhio = Integer.valueOf(getParameter(request, "anhio"));
    //
    //        int genero = Integer.valueOf(getParameter(request, "genero"));
    //        int interprete = Integer.valueOf(getParameter(request, "interprete"));

    String url = "";
    try {

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        String imagen = "images/";

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory(1024 * 4, new File("c;//tmp"));

        // Configure a repository (to ensure a secure temp location is used)
        ServletContext servletContext = this.getServletConfig().getServletContext();
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);

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

        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if (item.isFormField()) {
                if (item.getFieldName().equals("nombre")) {
                    nombre = item.getString();
                } else if (item.getFieldName().equals("anhio")) {
                    anhio = Integer.valueOf(item.getString());
                } else if (item.getFieldName().equals("genero")) {
                    genero = Short.valueOf(item.getString());
                } else if (item.getFieldName().equals("interprete")) {
                    interprete = Integer.valueOf(item.getString());
                } else if (item.getFieldName().equals("precio")) {
                    precio = Long.valueOf(item.getString());
                }

            } else {
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();

                //                    InputStream uploadedStream = item.getInputStream();
                //                    uploadedStream.close();
                //                    InputStream uploadedStream = item.getInputStream();
                //                    uploadedStream.close();
                imagen = imagen + fileName;
                File uploadedFile = new File(RUTA + fileName);

                item.write(uploadedFile);
                //                    } else {
                //                        
                //                    }
            }
        }

        java.util.Calendar cl = java.util.Calendar.getInstance();
        cl.set(anhio, 0, 0, 0, 0, 0);

        Disco disco = new Disco();
        disco.setGenero(generoFacade.find(genero));
        disco.setInterprete(interpreteFacade.find(interprete));
        disco.setNombre(nombre);
        disco.setImagen(imagen);
        disco.setAnhio(cl.getTime());

        discoFacade.create(disco);

        if (disco.getId() != null) {

            Discopropietario dp = new Discopropietario();
            dp.setDisco(disco);
            dp.setPropietario((Persona) request.getSession().getAttribute("usuario"));
            dp.setPrecio(precio);
            dp.setVendido(false);

            dpFacade.create(dp);

            url = "disco?id=" + disco.getId();

        } else {
            url = "fdisco?nombre=" + nombre + "&precio=" + precio + "&anhio=" + anhio + "&genero=" + genero
                    + "&interprete=" + interprete;
        }

    } catch (FileUploadException ex) {
        Logger.getLogger(GuardarDisco.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(GuardarDisco.class.getName()).log(Level.SEVERE, null, ex);
    }

    response.sendRedirect(url);

}

From source file:com.ephesoft.dcma.gwt.uploadbatch.server.UploadBatchImageServlet.java

private void uploadFile(HttpServletRequest req, HttpServletResponse resp, BatchSchemaService batchSchemaService,
        String currentBatchUploadFolderName) throws IOException {
    PrintWriter printWriter = resp.getWriter();
    File tempFile = null;/*from  www .  j a  va 2  s.  c  om*/
    InputStream instream = null;
    OutputStream out = null;
    String uploadBatchFolderPath = batchSchemaService.getUploadBatchFolder();
    String uploadFileName = "";
    if (ServletFileUpload.isMultipartContent(req)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        uploadFileName = "";
        String uploadFilePath = "";
        List<FileItem> items;
        try {
            items = upload.parseRequest(req);

            for (FileItem item : items) {
                if (!item.isFormField()) { // && "uploadFile".equals(item.getFieldName())) {
                    uploadFileName = item.getName();
                    if (uploadFileName != null) {
                        uploadFileName = uploadFileName
                                .substring(uploadFileName.lastIndexOf(File.separator) + 1);
                    }
                    uploadFilePath = uploadBatchFolderPath + File.separator + currentBatchUploadFolderName
                            + File.separator + uploadFileName;

                    try {
                        instream = item.getInputStream();
                        tempFile = new File(uploadFilePath);

                        out = new FileOutputStream(tempFile);
                        byte buf[] = new byte[1024];
                        int len = instream.read(buf);
                        while (len > 0) {
                            out.write(buf, 0, len);
                            len = instream.read(buf);
                        }
                    } catch (FileNotFoundException e) {
                        LOG.error("Unable to create the upload folder." + e, e);
                        printWriter.write("Unable to create the upload folder.Please try again.");

                    } catch (IOException e) {
                        LOG.error("Unable to read the file." + e, e);
                        printWriter.write("Unable to read the file.Please try again.");
                    } finally {
                        if (out != null) {
                            out.close();
                        }
                        if (instream != null) {
                            instream.close();
                        }
                    }
                }
            }
        } catch (FileUploadException e) {
            LOG.error("Unable to read the form contents." + e, e);
            printWriter.write("Unable to read the form contents.Please try again.");
        }

    } else {
        LOG.error("Request contents type is not supported.");
        printWriter.write("Request contents type is not supported.");
    }
    printWriter.write("currentBatchUploadFolderName:" + currentBatchUploadFolderName);
    printWriter.append("|");

    printWriter.append("fileName:").append(uploadFileName);
    printWriter.append("|");

    printWriter.flush();
}

From source file:Controle.Controle_foto.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    ArrayList<Object> obj = new ArrayList<Object>();
    Mensagem msg = new Mensagem();
    Gson gson = new Gson();
    PrintWriter out = response.getWriter();

    Foto foto = new Foto();
    FotoDAO fotoDAO = new FotoDAO();

    System.out.println("teste");
    if (isMultipart) {
        System.out.println("teste2");
        FileItemFactory factory = new DiskFileItemFactory();
        System.out.println("teste3");
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {//from  w ww .j a  v a 2 s  . com
            System.out.println("teste4");
            List itens = upload.parseRequest(request);
            Iterator iterator = itens.iterator();
            String id = "";
            String legenda = "";
            id = request.getParameter("id");
            //                
            //                if(id.equals("null")){
            //                    System.out.println("sem id da foto");
            //                }else{
            //                    System.out.println("com id da foto");
            //                }

            System.out.println("id da foto: " + request.getParameter("id"));

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

                if (!item.isFormField()) {
                    String nomeArquivo = item.getName();
                    String extensao = "";

                    System.out.println(nomeArquivo);
                    int cont = 4;
                    for (int i = 0; i <= 3; i++) {
                        extensao += nomeArquivo.charAt(nomeArquivo.length() - cont);
                        cont = cont - 1;
                    }
                    Random rdm = new Random();
                    int n = rdm.nextInt(99999);
                    nomeArquivo = id + n + extensao;

                    System.out.println(nomeArquivo);
                    String diretorio = getServletContext().getRealPath("/");
                    File destino = new File(diretorio + "/segura/img");
                    System.out.println(destino);

                    //apagar arquivo antigo.

                    foto = fotoDAO.buscarPorId(Integer.parseInt(id));

                    if (foto.getId() <= 0) {
                        throw new Exception("Foto no encontrada!!!!");
                    } else {
                        File arquivoAntigo = new File(diretorio + "/" + foto.getEndereco());
                        System.out.println("Endereo da imagem antiga !!!!!!!!!" + foto.getEndereco());
                        if (!foto.getEndereco().equals("segura/default/sem_foto.jpg")) {
                            boolean bool = arquivoAntigo.delete();
                            System.out.println("arquivo apagado? " + bool);
                            System.out.println("O seguinte arquivo antigo foi apagardo!!!!!!!!!"
                                    + arquivoAntigo.getAbsolutePath());
                        }
                        foto.setEndereco("/segura/img/" + nomeArquivo);
                        foto.setLegenda(legenda);
                        fotoDAO.atualizar(foto);
                    }

                    //                        if (!destino.exists()) {
                    //                            boolean status = destino.mkdirs();
                    //
                    //                        }
                    File arquivoRecebido = new File(destino + "/" + nomeArquivo);
                    System.out.println(arquivoRecebido.getAbsolutePath());

                    item.write(arquivoRecebido);

                } else {
                    if (!item.getFieldName().equals("legenda")) {
                        id = item.getString();
                    } else {
                        legenda = item.getString();
                    }

                    System.out.println("Nome do campo !!!" + item.getFieldName());
                    System.out.println("Olha o valor do id  !!!" + item.getString());

                }

            }
            msg.setMensagem("Cadastrado com sucesso!!!!");
            msg.setTipo(1);
            obj.add(msg);
        } catch (FileUploadException e) {
            e.printStackTrace();
            System.out.println("Erro!!" + e.getMessage());
            msg.setMensagem("Erro!!" + e.getMessage());
            msg.setTipo(2);
            obj.add(msg);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Erro!!" + e.getMessage());
            msg.setMensagem("Erro!!" + e.getMessage());
            msg.setTipo(2);
            obj.add(msg);
        } finally {
            out.printf(gson.toJson(obj));
        }
    } else {
        System.out.println("deu ruim no multpart");
    }
}