Example usage for org.apache.commons.fileupload FileItem getString

List of usage examples for org.apache.commons.fileupload FileItem getString

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getString.

Prototype

String getString();

Source Link

Document

Returns the contents of the file item as a String, using the default character encoding.

Usage

From source file:admin.controller.ServletAddLooks.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  ww w .j  av  a 2 s.  c  o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    super.processRequest(request, response);
    String filePath;
    String fileName, fieldName;
    Looks look;
    RequestDispatcher request_dispatcher;
    String look_name = null;
    Integer organization_id = 0;
    boolean check;
    look = new Looks();
    check = false;

    response.setContentType("text/html;charset=UTF-8");
    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {
        String uploadPath = AppConstants.LOOK_IMAGES_HOME;

        // Verify the content type
        String contentType = request.getContentType();
        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("/tmp"));

            // 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(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
                    fieldName = fi.getFieldName();
                    try {
                        if (fieldName.equals("lookname")) {
                            look_name = fi.getString();
                        }
                        if (fieldName.equals("organization")) {
                            organization_id = Integer.parseInt(fi.getString());
                        }
                    } catch (Exception e) {
                        logger.log(Level.SEVERE, "Exception while getting the look_name and organization_id",
                                e);
                    }
                } else {
                    check = look.checkAvailability(look_name, organization_id);

                    if (check == false) {
                        fieldName = fi.getFieldName();
                        fileName = fi.getName();

                        File uploadDir = new File(uploadPath);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        //                            int inStr = fileName.indexOf(".");
                        //                            String Str = fileName.substring(0, inStr);
                        //
                        //                            fileName = look_name + "_" + Str + ".png";
                        fileName = look_name + "_" + fileName;
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);

                        fi.write(storeFile);

                        look.addLooks(look_name, fileName, organization_id);
                        response.sendRedirect(request.getContextPath() + "/admin/looks.jsp");
                    } else {
                        response.sendRedirect(request.getContextPath() + "/admin/looks.jsp?exist=exist");
                    }

                }
            }

        } else {
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception while uploading the Looks image", ex);
    }
}

From source file:admin.controller.ServletAddPersonality.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w  w  w .  j a v  a2  s  . 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
 */
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        String uploadPath = AppConstants.BRAND_IMAGES_HOME;

        // Verify the content type
        String contentType = request.getContentType();
        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("/tmp"));

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

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

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    field_name = fi.getFieldName();
                    if (field_name.equals("brandname")) {
                        brand_name = fi.getString();
                    }
                    if (field_name.equals("look")) {
                        look_id = fi.getString();
                    }

                } else {
                    check = brand.checkAvailability(brand_name);

                    if (check == false) {
                        field_name = fi.getFieldName();
                        file_name = fi.getName();

                        File uploadDir = new File(uploadPath);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        //                                int inStr = file_name.indexOf(".");
                        //                                String Str = file_name.substring(0, inStr);
                        //                                file_name = brand_name + "_" + Str + ".jpeg";

                        file_name = brand_name + "_" + file_name;
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        String filePath = uploadPath + File.separator + file_name;
                        File storeFile = new File(filePath);

                        fi.write(storeFile);
                        brand.addBrands(brand_name, Integer.parseInt(look_id), file_name);

                        response.sendRedirect(request.getContextPath() + "/admin/brandpersonality.jsp");

                        out.println("Uploaded Filename: " + filePath + "<br>");
                    } else {
                        response.sendRedirect(
                                request.getContextPath() + "/admin/brandpersonality.jsp?exist=exist");
                    }
                }
            }
            out.println("</body>");
            out.println("</html>");
        } else {
            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>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "", ex);
    } finally {
        try {
            out.close();
        } catch (Exception e) {
            logger.log(Level.SEVERE, "", e);
        }
    }

}

From source file:admin.controller.ServletChangeLooks.java

/**
  * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
  * methods./* ww w .j  a v  a  2s.  co m*/
  *
  * @param request servlet request
  * @param response servlet response
  * @throws ServletException if a servlet-specific error occurs
  * @throws IOException if an I/O error occurs
  */
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String filePath = "";
    String fileName, fieldName, uploadPath, deletePath, file_name_to_delete = "", uploadPath1;
    Looks look;
    RequestDispatcher request_dispatcher;
    String lookname = "", lookid = "";
    Integer organization = 0;
    look = new Looks();
    boolean check = false;

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {
        // Verify the content type
        String contentType = request.getContentType();
        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(AppConstants.TMP_FOLDER));

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

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

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    if (fieldName.equals("lookname")) {
                        lookname = fi.getString();
                    }
                    if (fieldName.equals("lookid")) {
                        lookid = fi.getString();
                    }
                    if (fieldName.equals("organization")) {
                        organization = Integer.parseInt(fi.getString());
                    }
                    file_name_to_delete = look.getFileName(Integer.parseInt(lookid));
                } else {

                    check = look.checkAvailabilities(Integer.parseInt(lookid), lookname, organization);

                    if (check == false) {

                        fieldName = fi.getFieldName();
                        fileName = fi.getName();

                        File uploadDir = new File(AppConstants.LOOK_IMAGES_HOME);

                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        //                            int inStr = fileName.indexOf(".");
                        //                            String Str = fileName.substring(0, inStr);
                        //
                        //                            fileName = lookname + "_" + Str + ".png";
                        fileName = lookname + "_" + fileName;
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        String file_path = AppConstants.LOOK_IMAGES_HOME + File.separator + fileName;
                        String delete_path = AppConstants.LOOK_IMAGES_HOME + File.separator
                                + file_name_to_delete;
                        File deleteFile = new File(delete_path);
                        deleteFile.delete();
                        File storeFile = new File(file_path);
                        fi.write(storeFile);
                        out.println("Uploaded Filename: " + filePath + "<br>");
                        look.changeLooks(Integer.parseInt(lookid), lookname, fileName, organization);
                        response.sendRedirect(request.getContextPath() + "/admin/looks.jsp");
                    } else {
                        response.sendRedirect(
                                request.getContextPath() + "/admin/editlook.jsp?exist=exist&look_id=" + lookid
                                        + "&look_name=" + lookname + "&organization_id=" + organization
                                        + "&image_file_name=" + file_name_to_delete);
                    }
                }
            }
            out.println("</body>");
            out.println("</html>");
        } else {
            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>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception while editing the looks", ex);
    } finally {
        out.close();
    }

}

From source file:admin.controller.ServletEditCategories.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w  ww.  j a  va  2s .  c o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        upload_path = AppConstants.ORG_CATEGORIES_HOME;

        // Verify the content type
        String contentType = request.getContentType();
        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(AppConstants.TMP_FOLDER));

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

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

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    field_name = fi.getFieldName();
                    if (field_name.equals("category_name")) {
                        category_name = fi.getString();
                    }
                    if (field_name.equals("category_id")) {
                        category_id = fi.getString();
                    }
                    if (field_name.equals("organization")) {
                        organization_id = fi.getString();
                        upload_path = upload_path + File.separator + organization_id;
                    }

                } else {
                    field_name = fi.getFieldName();
                    file_name = fi.getName();

                    if (file_name != "") {
                        File uploadDir = new File(upload_path);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        //                            int inStr = file_name.indexOf(".");
                        //                            String Str = file_name.substring(0, inStr);
                        //
                        //                            file_name = category_name + "_" + Str + ".jpeg";
                        file_name = category_name + "_" + file_name;
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        String filePath = upload_path + File.separator + file_name;
                        File storeFile = new File(filePath);

                        fi.write(storeFile);

                        out.println("Uploaded Filename: " + filePath + "<br>");
                    }
                }
            }
            categories.editCategories(Integer.parseInt(category_id), Integer.parseInt(organization_id),
                    category_name, file_name);
            response.sendRedirect(request.getContextPath() + "/admin/categories.jsp");
            out.println("</body>");
            out.println("</html>");
        } else {
            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>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception while editing categories", ex);
    } finally {
        try {
            out.close();
        } catch (Exception e) {
        }
    }

}

From source file:admin.controller.ServletAddCategories.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w  w  w .  j a v a2s  .  co m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        String uploadPath = AppConstants.ORG_CATEGORIES_HOME;

        // Verify the content type
        String contentType = request.getContentType();
        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(AppConstants.TMP_FOLDER));

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

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

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    field_name = fi.getFieldName();
                    if (field_name.equals("category_name")) {
                        category_name = fi.getString();
                    }
                    if (field_name.equals("organization")) {
                        organization_id = fi.getString();
                        uploadPath = uploadPath + File.separator + organization_id;
                    }

                } else {

                    field_name = fi.getFieldName();
                    file_name = fi.getName();
                    if (file_name != "") {
                        check = categories.checkAvailability(category_name, Integer.parseInt(organization_id));
                        if (check == false) {
                            File uploadDir = new File(uploadPath);
                            if (!uploadDir.exists()) {
                                uploadDir.mkdirs();
                            }

                            //we need to save file name directly
                            //                                int inStr = file_name.indexOf(".");
                            //                                String Str = file_name.substring(0, inStr);
                            //                                file_name = category_name + "_" + Str + ".jpeg";

                            file_name = category_name + "_" + file_name;
                            boolean isInMemory = fi.isInMemory();
                            long sizeInBytes = fi.getSize();

                            String filePath = uploadPath + File.separator + file_name;
                            File storeFile = new File(filePath);

                            fi.write(storeFile);
                            categories.addCategories(Integer.parseInt(organization_id), category_name,
                                    file_name);

                            out.println("Uploaded Filename: " + filePath + "<br>");
                            response.sendRedirect(request.getContextPath() + "/admin/categories.jsp");
                        } else {
                            response.sendRedirect(
                                    request.getContextPath() + "/admin/categories.jsp?exist=exist");
                        }
                    }
                }
            }
            out.println("</body>");
            out.println("</html>");
        } else {
            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>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception while adding categories", ex);
    } finally {
        out.close();
    }
}

From source file:net.ion.radon.impl.let.webdav.FCKConnectorRestlet.java

protected void handlePost(final Request request, final Response response, final String currentFolderStr) {
    final Form parameters = request.getResourceRef().getQueryAsForm();
    final String commandStr = parameters.getValues("Command");

    String retVal = "0";
    String newName = "";

    if (!commandStr.equalsIgnoreCase("FileUpload"))
        retVal = "203";
    else {/*from   w ww. j  a v a2 s.  com*/
        final RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory());
        try {
            final List<?> items = upload.parseRequest(request);

            final Map<String, Object> fields = new HashMap<String, Object>();

            final Iterator<?> iterator = items.iterator();
            while (iterator.hasNext()) {
                final FileItem item = (FileItem) iterator.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString());
                else
                    fields.put(item.getFieldName(), item);
            }

            final FileItem uploadFile = (FileItem) fields.get("NewFile");
            String fileNameLong = uploadFile.getName();
            fileNameLong = fileNameLong.replace('\\', '/');
            final String[] pathParts = fileNameLong.split("/");
            final String fileName = pathParts[pathParts.length - 1];

            final String nameWithoutExt = getNameWithoutExtension(fileName);
            final String ext = getExtension(fileName);
            File pathToSave = new File(currentFolderStr, fileName);

            int counter = 1;
            while (pathToSave.exists()) {
                newName = nameWithoutExt + "(" + (counter++) + ")" + "." + ext;
                retVal = "201";
                pathToSave = new File(currentFolderStr, newName);
            }

            try {
                OutputStream fout = vfs.getOutputStream(VFSUtils.parseVFSPath(pathToSave.getPath()));
                fout.write(uploadFile.get());
                fout.close();
            } catch (Exception e) {
            }

            // uploadFile.write(pathToSave);
        } catch (final Exception e) {
            e.printStackTrace();
            retVal = "203";
        }
    }

    response.setStatus(Status.SUCCESS_OK);
    Form headers = (Form) response.getAttributes().get("org.restlet.http.headers");
    if (headers == null) {
        headers = new Form();
        response.getAttributes().put("org.restlet.http.headers", headers);
    }
    headers.add("Content-type", "text/xml; charset=UTF-8");
    headers.add("Cache-control", "no-cache");

    String script = "<html><head><title></title><script type=\"text/javascript\">";
    script += "function doWork() {";
    script += "window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');";
    // script += "window.parent.OnUploadComplete(" + retVal + ",'" + newName + "', '" + newName + "');";
    // script += "window.location.reload(true);";
    script += "}</script></head><body onload=\"doWork()\">Upload done!</body></html>";
    response.setEntity(new StringRepresentation(script, MediaType.TEXT_HTML));

    // System.out.println(script);
}

From source file:com.gwtcx.server.servlet.FileUploadServlet.java

@SuppressWarnings("rawtypes")
private void processFiles(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

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

    // set the size threshold, above which content will be stored on disk
    factory.setSizeThreshold(1 * 1024 * 1024); // 1 MB

    // set the temporary directory (this is where files that exceed the threshold will be stored)
    factory.setRepository(tmpDir);/*from  ww  w . j a  v  a  2s .c o m*/

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

    try {
        String recordType = "Account";

        // parse the request
        List items = upload.parseRequest(request);

        // process the uploaded items
        Iterator itr = items.iterator();

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

            // process a regular form field
            if (item.isFormField()) {
                Log.debug("Field Name: " + item.getFieldName() + ", Value: " + item.getString());

                if (item.getFieldName().equals("recordType")) {
                    recordType = item.getString();
                }
            } else { // process a file upload

                Log.debug("Field Name: " + item.getFieldName() + ", Value: " + item.getName()
                        + ", Content Type: " + item.getContentType() + ", In Memory: " + item.isInMemory()
                        + ", File Size: " + item.getSize());

                // write the uploaded file to the application's file staging area
                File file = new File(destinationDir, item.getName());
                item.write(file);

                // import the CSV file
                importCsvFile(recordType, file.getPath());

                // file.delete();  // TO DO
            }
        }
    } catch (FileUploadException e) {
        Log.error("Error encountered while parsing the request", e);
    } catch (Exception e) {
        Log.error("Error encountered while uploading file", e);
    }
}

From source file:com.silverpeas.form.form.XmlSearchForm.java

private String getParameterValues(List<FileItem> items, String parameterName) {
    SilverTrace.debug("form", "XmlSearchForm.getParameterValues", "root.MSG_GEN_ENTER_METHOD",
            "parameterName = " + parameterName);
    String values = "";
    List<FileItem> params = getParameters(items, parameterName);
    FileItem item = null;
    for (int p = 0; p < params.size(); p++) {
        item = params.get(p);/*from w  w  w . ja  v a2  s . c  o m*/
        values += item.getString();
        if (p < params.size() - 1) {
            values += "##";
        }
    }
    SilverTrace.debug("form", "XmlSearchForm.getParameterValues", "root.MSG_GEN_EXIT_METHOD",
            "parameterValue = " + values);
    return values;
}

From source file:com.dotmarketing.portlets.cmsmaintenance.ajax.IndexAjaxAction.java

public void restoreIndex(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DotDataException {
    try {/*from   www.  j a  v  a2s .  c  om*/
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = (List<FileItem>) upload.parseRequest(request);

        String indexToRestore = null;
        boolean clearBeforeRestore = false;
        String aliasToRestore = null;
        File ufile = null;
        boolean isFlash = false;
        for (FileItem it : items) {
            if (it.getFieldName().equalsIgnoreCase("indexToRestore")) {
                indexToRestore = it.getString().trim();
            } else if (it.getFieldName().equalsIgnoreCase("aliasToRestore")) {
                aliasToRestore = it.getString().trim();
            } else if (it.getFieldName().equalsIgnoreCase("uploadedfiles[]")
                    || it.getFieldName().equals("uploadedfile")
                    || it.getFieldName().equalsIgnoreCase("uploadedfileFlash")) {
                isFlash = it.getFieldName().equalsIgnoreCase("uploadedfileFlash");
                ufile = File.createTempFile("indexToRestore", "idx");
                InputStream in = it.getInputStream();
                FileOutputStream out = new FileOutputStream(ufile);
                IOUtils.copyLarge(in, out);
                IOUtils.closeQuietly(out);
                IOUtils.closeQuietly(in);
            } else if (it.getFieldName().equalsIgnoreCase("clearBeforeRestore")) {
                clearBeforeRestore = true;
            }
        }

        if (LicenseUtil.getLevel() >= 200) {
            if (UtilMethods.isSet(aliasToRestore)) {
                String indexName = APILocator.getESIndexAPI()
                        .getAliasToIndexMap(APILocator.getSiteSearchAPI().listIndices()).get(aliasToRestore);
                if (UtilMethods.isSet(indexName))
                    indexToRestore = indexName;
            } else if (!UtilMethods.isSet(indexToRestore)) {
                indexToRestore = APILocator.getIndiciesAPI().loadIndicies().site_search;
            }
        }

        if (ufile != null) {
            final boolean clear = clearBeforeRestore;
            final String index = indexToRestore;
            final File file = ufile;
            new Thread() {
                public void run() {
                    try {
                        if (clear)
                            APILocator.getESIndexAPI().clearIndex(index);
                        APILocator.getESIndexAPI().restoreIndex(file, index);
                        Logger.info(this, "finished restoring index " + index);
                    } catch (Exception ex) {
                        Logger.error(IndexAjaxAction.this, "Error restoring", ex);
                    }
                }
            }.start();

        }

        PrintWriter out = response.getWriter();
        if (isFlash) {
            out.println("response=ok");
        } else {
            response.setContentType("application/json");
            out.println("{\"response\":1}");
        }

    } catch (FileUploadException fue) {
        Logger.error(this, "Error uploading file", fue);
        throw new IOException(fue);
    }
}

From source file:FYPManagementSystem.FileUploadHandler.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String address = "";

    String option = request.getParameter("Option");
    String addTitle = "";
    String addContent = "";

    String query = "";
    String queryLastID = "";
    DB objDB = new DB();
    //process only if its multipart content
    if (option.equals("Add")) {

        if (ServletFileUpload.isMultipartContent(request)) {
            try {

                List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory())
                        .parseRequest(request);

                for (FileItem item : multiparts) {
                    if (!item.isFormField()) {
                        String name = new File(item.getName()).getName();
                        item.write(new File(UPLOAD_DIRECTORY + File.separator + addTitle + ".jpg"));
                    } else if (item.isFormField()) {
                        if (item.getFieldName().contentEquals("addTitle")) { //Check if the item in the loop is the user_id
                            addTitle = item.getString(); //If yes store the value
                        }// w ww.  ja  va 2 s  .co  m
                        if (item.getFieldName().contentEquals("addContent")) { //Check if the item in the loop is the user_id
                            addContent = item.getString(); //If yes store the value
                        }
                    }
                }
                query = "insert into news (newsTitle,newsContent) values('"
                        + Common.replaceSingleQuote(addTitle) + "','" + Common.replaceSingleQuote(addContent)
                        + "')";

                //File uploaded successfully
                request.setAttribute("message", "File Uploaded Successfully");
            } catch (Exception ex) {
                request.setAttribute("message", "File Upload Failed due to " + ex);
            }
            address = "WEB-INF/AdNews.jsp";
        } else {
            request.setAttribute("message", "Sorry this Servlet only handles file upload request");
        }
    }
    objDB.connect();
    objDB.query(query);
    objDB.close();

    RequestDispatcher dispatcher = request.getRequestDispatcher(address);
    dispatcher.forward(request, response);

}