Example usage for org.apache.commons.fileupload.disk DiskFileItemFactory setRepository

List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setRepository

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.disk DiskFileItemFactory setRepository.

Prototype

public void setRepository(File repository) 

Source Link

Document

Sets the directory used to temporarily store files that are larger than the configured size threshold.

Usage

From source file:ch.zhaw.init.walj.projectmanagement.admin.properties.AdminProperties.java

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

    boolean isMultipart;
    String filePath;//from   w w  w  .  ja  va2 s  .  c o m
    int maxFileSize = 9000 * 1024;
    int maxMemSize = 4 * 1024;
    File file;

    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");

    boolean small = request.getParameter("size").equals("small");

    String message;

    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(this.getServletContext().getRealPath("/") + "img/"));

    // 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<FileItem> fileItems = upload.parseRequest(request);

        // Process the uploaded file items

        for (FileItem fileItem : fileItems) {

            if (!fileItem.isFormField()) {
                // Get the uploaded file parameters
                String contentType = fileItem.getContentType();
                if (contentType.equals("image/png")) {
                    String fileName;
                    if (small) {
                        fileName = "logo_small.png";
                    } else {
                        fileName = "logo.png";
                    }
                    filePath = this.getServletContext().getRealPath("/") + "img/" + fileName;
                    // Write the file
                    file = new File(filePath);
                    fileItem.write(file);
                } else {
                    throw new Exception("type");
                }
            }
        }
        message = "<div class=\"row\">" + "<div class=\"small-12 columns\">" + "<div class=\"row\">"
                + "<div class=\"callout success\">" + "<h5>Logo uploaded successfully</h5>" + "</div>"
                + "</div>" + "</div>" + "</div>";
        request.setAttribute("msg", message);
    } catch (Exception ex) {

        if (ex.getMessage().equals("type")) {

            message = "<div class=\"row\">" + "<div class=\"small-12 columns\">" + "<div class=\"row\">"
                    + "<div class=\"callout alert\">" + "<h5>Wrong Type</h5>"
                    + "<p>Please upload a PNG image</p>" + "</div>" + "</div>" + "</div>" + "</div>";
        } else {
            message = "<div class=\"row\">" + "<div class=\"small-12 columns\">" + "<div class=\"row\">"
                    + "<div class=\"callout alert\">" + "<h5>Upload failed</h5>" + "</div>" + "</div>"
                    + "</div>" + "</div>";
        }
        request.setAttribute("msg", message);
    }
    doGet(request, response);
}

From source file:UploadImageEdit.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   ww  w.  ja  v  a  2s.com*/
 *
 * @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, FileUploadException, IOException_Exception {
    // Check that we have a file upload request
    PrintWriter writer = response.getWriter();
    String productName = "";
    String description = "";
    String price = "";
    String pictureName = "";
    String productId = "";

    Cookie cookie = null;
    Cookie[] cookies = null;
    String selectedCookie = "";
    // Get an array of Cookies associated with this domain
    cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            cookie = cookies[i];
            if (cookie.getName().equals("JuraganDiskon")) {
                selectedCookie = cookie.getValue();
            }
        }
    } else {
        writer.println("<h2>No cookies founds</h2>");
    }

    if (!ServletFileUpload.isMultipartContent(request)) {
        // if not, we stop here

        writer.println("Error: Form must has enctype=multipart/form-data.");
        writer.flush();
        return;
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // sets memory threshold - beyond which files are stored in disk
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    // sets temporary location to store files
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);

    // sets maximum size of upload file
    upload.setFileSizeMax(MAX_FILE_SIZE);

    // sets maximum size of request (include file + form data)
    upload.setSizeMax(MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    // this path is relative to application's directory
    String uploadPath = new File(new File(getServletContext().getRealPath("")).getParent()).getParent()
            + "/web/" + UPLOAD_DIRECTORY;

    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    try {
        // parses the request's content to extract file data
        @SuppressWarnings("unchecked")
        List<FileItem> formItems = upload.parseRequest(request);

        if (formItems != null && formItems.size() > 0) {
            // iterates over form's fields
            int k = 0;
            for (FileItem item : formItems) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    k++;
                    writer.println("if = " + k);

                    String fileName = new File(item.getName()).getName();
                    pictureName = fileName;
                    String filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);

                    // saves the file on disk
                    item.write(storeFile);
                    request.setAttribute("message", "Upload has been done successfully!");
                    writer.println("pictureName = " + pictureName);
                } else {
                    k++;
                    writer.println("else = " + k);

                    // Get the field name
                    String fieldName = item.getName();
                    // Get the field value
                    String value = item.getString();
                    if (k == 0) {

                    } else if (k == 1) {
                        productId = value.trim();
                        writer.println("productId = " + productId);
                    } else if (k == 2) {
                        productName = value;
                        writer.println("productName = " + productName);
                    } else if (k == 3) {
                        description = value;
                        writer.println("description = " + description);
                    } else if (k == 4) {
                        price = value;
                        writer.println("price = " + price);
                    }

                }

            }
        }

    } catch (Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }
    String update = editTheProduct(Integer.valueOf(productId), productName, price, description, pictureName,
            selectedCookie);
    writer.println(update);

    //redirects client to message page
    getServletContext().getRequestDispatcher("/yourProduct.jsp").forward(request, response);

}

From source file:hoot.services.controllers.ingest.BasemapResource.java

@POST
@Path("/upload")
@Produces(MediaType.TEXT_PLAIN)//from   w  w  w.  ja  va  2s . c  o  m
public Response processUpload(@QueryParam("INPUT_NAME") final String inputName,
        @QueryParam("PROJECTION") final String projection, @Context HttpServletRequest request) {
    String groupId = UUID.randomUUID().toString();
    JSONArray jobsArr = new JSONArray();
    try {
        File uploadDir = new File(homeFolder + "/upload/");
        uploadDir.mkdir();

        String repFolderPath = homeFolder + "/upload/" + groupId;
        File dir = new File(repFolderPath);
        dir.mkdir();

        if (!ServletFileUpload.isMultipartContent(request)) {
            throw new ServletException("Content type is not multipart/form-data");
        }
        DiskFileItemFactory fileFactory = new DiskFileItemFactory();
        File filesDir = new File(repFolderPath);
        fileFactory.setRepository(filesDir);
        ServletFileUpload uploader = new ServletFileUpload(fileFactory);

        Map<String, String> uploadedFiles = new HashMap<String, String>();
        Map<String, String> uploadedFilesPaths = new HashMap<String, String>();
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();

        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();
            String fileName = fileItem.getName();

            String uploadedPath = repFolderPath + "/" + fileName;
            File file = new File(uploadedPath);
            fileItem.write(file);

            String[] nameParts = fileName.split("\\.");
            if (nameParts.length > 1) {
                String extension = nameParts[nameParts.length - 1].toLowerCase();
                String filename = nameParts[0];

                if (_basemapRasterExt.get(extension) != null) {
                    uploadedFiles.put(filename, extension);
                    uploadedFilesPaths.put(filename, fileName);
                    log.debug("Saving uploaded:" + filename);
                }

            }

        }

        Iterator it = uploadedFiles.entrySet().iterator();
        while (it.hasNext()) {
            String jobId = UUID.randomUUID().toString();
            Map.Entry pairs = (Map.Entry) it.next();
            String fName = pairs.getKey().toString();
            String ext = pairs.getValue().toString();

            log.debug("Preparing Basemap Ingest for :" + fName);
            String inputFileName = "";
            String bmName = inputName;

            if (bmName != null && bmName.length() > 0) {
                bmName = bmName;
            } else {
                bmName = fName;
            }

            inputFileName = uploadedFilesPaths.get(fName);

            try {
                JSONArray commandArgs = new JSONArray();
                JSONObject arg = new JSONObject();
                arg.put("INPUT", "upload/" + groupId + "/" + inputFileName);
                commandArgs.add(arg);

                arg = new JSONObject();
                arg.put("INPUT_NAME", bmName);
                commandArgs.add(arg);

                arg = new JSONObject();
                arg.put("RASTER_OUTPUT_DIR", _tileServerPath + "/BASEMAP");
                commandArgs.add(arg);

                arg = new JSONObject();
                if (projection != null && projection.length() > 0) {
                    arg.put("PROJECTION", projection);
                } else {
                    arg.put("PROJECTION", "auto");
                }
                commandArgs.add(arg);

                arg = new JSONObject();
                arg.put("JOB_PROCESSOR_DIR", _ingestStagingPath + "/BASEMAP");
                commandArgs.add(arg);

                String argStr = createBashPostBody(commandArgs);
                postJobRquest(jobId, argStr);

                JSONObject res = new JSONObject();
                res.put("jobid", jobId);
                res.put("name", bmName);

                jobsArr.add(res);

            } catch (Exception ex) {
                ResourceErrorHandler.handleError("Error processing upload: " + ex.getMessage(),
                        Status.INTERNAL_SERVER_ERROR, log);
            }

        }

    } catch (Exception ex) {
        ResourceErrorHandler.handleError("Error processing upload: " + ex.getMessage(),
                Status.INTERNAL_SERVER_ERROR, log);
    }

    return Response.ok(jobsArr.toJSONString(), MediaType.APPLICATION_JSON).build();
}

From source file:edu.pitt.servlets.processAddMedia.java

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

    HttpSession session = request.getSession();
    String userID = (String) session.getAttribute("userID");

    String error = "select correct format ";
    session.setAttribute("error", error);

    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        // Process only if its multipart content
        // Create a factory for disk-based file items
        File file;
        // We might need to play with the file sizes
        int maxFileSize = 50000 * 1024;
        int maxMemSize = 50000 * 1024;
        ServletContext context = this.getServletContext();
        // Note that this file path refers to a virtual path
        // relative to this servlet.  The uploads directory
        // is part of this project.  The physical path varies 
        // from the virtual path

        String filePath = context.getRealPath("/uploads") + "/";
        out.println("Physical folder is located at: " + filePath + "<br />");

        // Verify the content type
        String contentType = request.getContentType();
        // This is very important - make sure that the web form that 
        // uploads the file is actually set to enctype="multipart/form-data"
        // An example of upload form for this project is in index.html
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            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(filePath));

            // 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();
                while (i.hasNext()) {
                    FileItem fi = (FileItem) i.next();
                    if (!fi.isFormField()) {
                        // Get the uploaded file parameters
                        String fieldName = fi.getFieldName();

                        out.println("field name" + fieldName);
                        String fileName = fi.getName();

                        out.println("file name" + fileName); // file name is present

                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();
                        //  out.println("file size"+ sizeInBytes);
                        // 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: " + filePath  + fileName + "<br />");
                        String savepath = filePath + fileName;

                        // to check correct format is entered or not 
                        int dotindex = fileName.indexOf(".");
                        if (!(fileName.substring(dotindex).matches(".ogv|.webm|.mp4|.png|.jpeg|.jpg|.gif"))) {
                            response.sendRedirect("./pages/addMedia.jsp");

                        }

                        // receives projectID from listProjects.jsp from edit href link , adding in existing project 
                        // corresponding constructor is used          
                        if (session.getAttribute("projectID") != null) {
                            Integer projectID = (Integer) session.getAttribute("projectID");

                            media = new Media(projectID, fileName);
                        }
                        // first time when user enters media for project , this constructor is used          
                        else {
                            media = new Media(userID, fileName);
                        }

                        System.out.println("Into the media constructor");
                        // redirected to listProject
                        response.sendRedirect("./pages/listProject.jsp");

                        // media constructor

                        // response.redirect(listprojects.jsp);

                        processRequest(request, response);
                    }

                }

            }

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

From source file:it.vige.greenarea.sgrl.servlet.CommonsFileUploadServlet.java

protected void workingdoPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("text/plain");
    out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
    out.println();/*from   ww  w .  j  a  v  a2s  .c  o m*/

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    /*
     * Set the size threshold, above which content will be stored on disk.
     */
    fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
    /*
     * Set the temporary directory to store the uploaded files of size above
     * threshold.
     */
    fileItemFactory.setRepository(tmpDir);

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        /*
         * Parse the request
         */
        List<FileItem> items = uploadHandler.parseRequest(request);
        Iterator<FileItem> itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            /*
             * Handle Form Fields.
             */
            if (item.isFormField()) {
                out.println("File Name = " + item.getFieldName() + ", Value = " + item.getString());
            } else {
                // Handle Uploaded files.
                out.println("Field Name = " + item.getFieldName() + ", File Name = " + item.getName()
                        + ", Content type = " + item.getContentType() + ", File Size = " + item.getSize());
                /*
                 * Write file to the ultimate location.
                 */
                File file = new File(destinationDir, "LogisticNetwork.mxe");
                item.write(file);
            }
            out.close();
        }
    } catch (FileUploadException ex) {
        log("Error encountered while parsing the request", ex);
    } catch (Exception ex) {
        log("Error encountered while uploading file", ex);
    }

}

From source file:com.sa.osgi.jetty.UploadServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from ww w .j a  v a2s.  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 {
    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

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

        // Configure a repository (to ensure a secure temp location is used)
        ServletContext servletContext = this.getServletConfig().getServletContext();
        String ss = servletContext.getInitParameter("javax.servlet.context.tempdir");
        File repository = new File("/tmp");//(File) servletContext.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);
        System.out.println("context var: " + ss);

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

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

                if (item.isFormField()) {
                    //                    processFormField(item);
                } else {
                    processUploadedFile(item);
                }
            }
        } catch (FileUploadException ex) {
            Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    response.sendRedirect("/welcome");

    //        RequestDispatcher dis = request.getRequestDispatcher("/welcome");
    //        dis.forward(request, response);

}

From source file:com.intelligentz.appointmentz.controllers.addSession.java

@SuppressWarnings("Since15")
@Override// w  w  w .  j  a v a  2s  .co m
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {
        String room_id = null;
        String doctor_id = null;
        String start_time = null;
        String date_picked = null;
        ArrayList<SessonCustomer> sessonCustomers = new ArrayList<>();
        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(filePath + "temp"));

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

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

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

        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) {
                    filePath = filePath + fileName.substring(fileName.lastIndexOf("\\"));
                    file = new File(filePath);
                } else {
                    filePath = filePath + fileName.substring(fileName.lastIndexOf("\\") + 1);
                    file = new File(filePath);
                }
                fi.write(file);
                Files.lines(Paths.get(filePath)).forEach((line) -> {
                    String[] cust = line.split(",");
                    sessonCustomers.add(new SessonCustomer(cust[0].trim(), Integer.parseInt(cust[1].trim())));
                });
            } else {
                if (fi.getFieldName().equals("room_id"))
                    room_id = fi.getString();
                else if (fi.getFieldName().equals("doctor_id"))
                    doctor_id = fi.getString();
                else if (fi.getFieldName().equals("start_time"))
                    start_time = fi.getString();
                else if (fi.getFieldName().equals("date_picked"))
                    date_picked = fi.getString();
            }
        }

        con = new connectToDB();
        if (con.connect()) {
            Connection connection = con.getConnection();
            Class.forName("com.mysql.jdbc.Driver");
            Statement stmt = connection.createStatement();
            String SQL, SQL1, SQL2;
            SQL1 = "insert into db_bro.session ( doctor_id, room_id, date, start_time) VALUES (?,?,?,?)";
            PreparedStatement preparedStmt = connection.prepareStatement(SQL1);
            preparedStmt.setString(1, doctor_id);
            preparedStmt.setString(2, room_id);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH:mm");
            try {
                java.util.Date d = formatter.parse(date_picked + "-" + start_time);
                Date d_sql = new Date(d.getTime());
                java.util.Date N = new java.util.Date();
                if (N.compareTo(d) > 0) {
                    res.sendRedirect("./error.jsp?error=Invalid Date!");
                }
                //String [] T = start_time.split(":");
                //Time t = Time.valueOf(start_time);
                //Time t = new Time(Integer.parseInt(T[0]),Integer.parseInt(T[1]),0);

                //java.sql.Time t_sql = new java.sql.Date(d.getTime());
                preparedStmt.setString(4, start_time + ":00");
                preparedStmt.setDate(3, d_sql);
            } catch (ParseException e) {
                displayMessage(res, "Invalid Date!" + e.getLocalizedMessage());
            }

            // execute the preparedstatement
            preparedStmt.execute();

            SQL = "select * from db_bro.session ORDER BY session_id DESC limit 1";
            ResultSet rs = stmt.executeQuery(SQL);

            boolean check = false;
            while (rs.next()) {
                String db_doctor_id = rs.getString("doctor_id");
                String db_date_picked = rs.getString("date");
                String db_start_time = rs.getString("start_time");
                String db_room_id = rs.getString("room_id");

                if ((doctor_id == null ? db_doctor_id == null : doctor_id.equals(db_doctor_id))
                        && (start_time == null ? db_start_time == null
                                : (start_time + ":00").equals(db_start_time))
                        && (room_id == null ? db_room_id == null : room_id.equals(db_room_id))
                        && (date_picked == null ? db_date_picked == null
                                : date_picked.equals(db_date_picked))) {
                    check = true;
                    //displayMessage(res,"Authentication Success!");
                    SQL2 = "insert into db_bro.session_customers ( session_id, mobile, appointment_num) VALUES (?,?,?)";
                    for (SessonCustomer sessonCustomer : sessonCustomers) {
                        preparedStmt = connection.prepareStatement(SQL2);
                        preparedStmt.setString(1, rs.getString("session_id"));
                        preparedStmt.setString(2, sessonCustomer.getMobile());
                        preparedStmt.setInt(3, sessonCustomer.getAppointment_num());
                        preparedStmt.execute();
                    }
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        displayMessage(res, "SQLException");
                    }

                    res.sendRedirect("./home");

                }
            }
            if (!check) {

                try {
                    connection.close();
                } catch (SQLException e) {
                    displayMessage(res, "SQLException");
                }
                displayMessage(res, "SQL query Failed!");
            }
        } else {
            con.showErrormessage(res);
        }

        /*res.setContentType("text/html");//setting the content type
        PrintWriter pw=res.getWriter();//get the stream to write the data
                
        //writing html in the stream
        pw.println("<html><body>");
        pw.println("Welcome to servlet: "+username);
        pw.println("</body></html>");
                
        pw.close();//closing the stream
        */
    } catch (Exception ex) {
        Logger.getLogger(authenticate.class.getName()).log(Level.SEVERE, null, ex);
        displayMessage(res, "Error!" + ex.getLocalizedMessage());
    }
}

From source file:com.antinymail.ventadecasas.servlet.UploadServlet.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  ava2s.c  om
    }
    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"));

    //factory.setRepository(new File("C:\\Users\\Susana\\Documents\\NetBeansProjects\\VentadeCasas\\web\\images")); 

    factory.setRepository(
            new File("C:\\Users\\Susana\\Documents\\NetBeansProjects\\VentadeCasas\\web\\images"));

    //factory.setRepository(new File("//petylde.esy.es//uploads//casapueblo"));
    //factory.setRepository(new Uri());

    // 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("\\")));

                    //file = new File( fileName);

                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));

                    //file = new File( fileName);
                }
                fi.write(file);
                //fi.write( fileNa ) ;  

                out.println("Uploaded Filename: " + fileName + "<br>");
                out.println("La ruta inicial era: " + filePath + "<br>");

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

From source file:com.mingsoft.basic.servlet.UploadServlet.java

/**
 * ?post//  ww  w .  jav a 2s . c om
 * @param req HttpServletRequest
 * @param res HttpServletResponse 
 * @throws ServletException ?
 * @throws IOException ?
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html;charset=utf-8");
    PrintWriter out = res.getWriter();
    String uploadPath = this.getServletContext().getRealPath(File.separator); // 
    String isRename = "";// ???? true:???
    String _tempPath = req.getServletContext().getRealPath(File.separator) + "temp";//
    FileUtil.createFolder(_tempPath);
    File tempPath = new File(_tempPath); // 

    int maxSize = 1000000; // ??,?? 1000000/1024=0.9M
    //String allowedFile = ".jpg,.gif,.png,.zip"; // ?
    String deniedFile = ".exe,.com,.cgi,.asp"; // ??

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    // ?????
    factory.setSizeThreshold(4096);
    // the location for saving data that is larger than getSizeThreshold()
    // ?SizeThreshold?
    factory.setRepository(tempPath);

    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum size before a FileUploadException will be thrown

    try {
        List fileItems = upload.parseRequest(req);

        Iterator iter = fileItems.iterator();

        // ????
        String regExp = ".+\\\\(.+)$";

        // 
        String[] errorType = deniedFile.split(",");
        Pattern p = Pattern.compile(regExp);
        String outPath = ""; //??
        while (iter.hasNext()) {

            FileItem item = (FileItem) iter.next();
            if (item.getFieldName().equals("uploadPath")) {
                outPath += item.getString();
                uploadPath += outPath;
            } else if (item.getFieldName().equals("isRename")) {
                isRename = item.getString();
            } else if (item.getFieldName().equals("maxSize")) {
                maxSize = Integer.parseInt(item.getString()) * 1048576;
            } else if (item.getFieldName().equals("allowedFile")) {
                //               allowedFile = item.getString();
            } else if (item.getFieldName().equals("deniedFile")) {
                deniedFile = item.getString();
            } else if (!item.isFormField()) { // ???
                String name = item.getName();
                long size = item.getSize();
                if ((name == null || name.equals("")) && size == 0)
                    continue;
                try {
                    // ?? 1000000/1024=0.9M
                    upload.setSizeMax(maxSize);

                    // ?
                    // ?
                    String fileName = System.currentTimeMillis() + name.substring(name.indexOf("."));
                    String savePath = uploadPath + File.separator;
                    FileUtil.createFolder(savePath);
                    // ???
                    if (StringUtil.isBlank(isRename) || Boolean.parseBoolean(isRename)) {
                        savePath += fileName;
                        outPath += fileName;
                    } else {
                        savePath += name;
                        outPath += name;
                    }
                    item.write(new File(savePath));
                    out.print(outPath.trim());
                    logger.debug("upload file ok return path " + outPath);
                    out.flush();
                    out.close();
                } catch (Exception e) {
                    this.logger.debug(e);
                }

            }
        }
    } catch (FileUploadException e) {
        this.logger.debug(e);
    }
}

From source file:commands.SendAnalysisRequest.java

@Override
public void execute(HttpServletRequest request, HttpServletResponse response, Controller controller) {
    //http://commons.apache.org/proper/commons-fileupload/using.html
    //process only if its multipart content
    String page = "Problem.jsp";
    if (ServletFileUpload.isMultipartContent(request)) {
        try {//from ww  w. j a  va2  s  . c  o  m
            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();

            // Configure a repository (to ensure a secure temp location is used)
            ServletContext servletContext = controller.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            System.out.println("File repository absolute path: " + repository.getAbsolutePath());

            factory.setRepository(repository);

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

            //parametros chave-valor (path valor)
            HashMap<String, String[]> params = new HashMap<String, String[]>();
            //parametros chave-valor para multimedia (path e array de bytes)
            HashMap<String, byte[]> mediaParams = new HashMap<String, byte[]>();

            // Tratando todos os parametros/itens da pagina (arquivos e no-arquivos)
            List<FileItem> items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                //key (path)
                FileItem item = iter.next();
                String key = item.getFieldName();

                if (item.isFormField()) {
                    //printFormField(item);
                    //value
                    String[] value = new String[1];
                    value[0] = item.getString();
                    params.put(key, value);
                } else {
                    //printUploadedFile(item);
                    byte[] value = item.get();
                    mediaParams.put(key, value);
                }
            }

            //File uploaded successfully
            //              request.setAttribute("message", "File Uploaded Successfully");
            long result = new ParamedicController().sendAnalysisRequest(params, 1, mediaParams);

            if (result == -1) {
                request.setAttribute("message", "Occurred a problem to sending analysis request");
            } else {
                request.setAttribute("idAnalysis", result);
                request.setAttribute("message", "Analysis request sent successfully");
                page = "AnalysisResponseSearch.jsp";
                //RequestDispatcher reqDispatcher = request.getRequestDispatcher("AnalysisResponseSearch.jsp");
                //reqDispatcher.forward(request, response);
            }

            //                request.getRequestDispatcher("AnalysisResponseSearch.jsp").forward(request, response);
        } catch (Exception ex) {
            request.setAttribute("message", "File Upload Failed due to " + ex);
            ex.printStackTrace();
        }

    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }
    try {
        request.getRequestDispatcher(page).forward(request, response);
    } catch (ServletException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}