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

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

Introduction

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

Prototype

public DiskFileItemFactory() 

Source Link

Document

Constructs an unconfigured instance of this class.

Usage

From source file:Emporium.Servlet.ServImportaVpne.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from ww w  .  ja  v a 2 s.co  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession sessao = request.getSession();
    String nomeBD = (String) sessao.getAttribute("nomeBD");

    boolean isMultiPart = FileUpload.isMultipartContent(request);
    int idCliente = 0, idDepartamento = 0;

    if (nomeBD != null) {
        if (isMultiPart) {
            try {
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setSizeMax(1024 * 1024 * 2);

                List items = upload.parseRequest(request);
                Iterator iter = items.iterator();
                ArrayList<FileItem> listaArq = new ArrayList<>();

                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField()) {

                        if (item.getFieldName().equals("idCliente")) {
                            idCliente = Integer.parseInt(item.getString());
                        }
                        if (item.getFieldName().equals("idDepartamento")) {
                            idDepartamento = Integer.parseInt(item.getString());
                        }
                    }
                    if (!item.isFormField()) {
                        if (item.getName().length() > 0) {
                            listaArq.add(item);
                        }
                    }
                }
                if (listaArq.isEmpty()) {
                    response.sendRedirect("Cliente/Servicos/vpne.jsp?msg=Escolha um arquivo para importacao !");
                } else if (listaArq.size() > 200) {
                    response.sendRedirect(
                            "Cliente/Servicos/vpne.jsp?msg=Importacao maxima de 200 arquivos de cada vez!");
                } else {

                    String condicao = ContrVpne.importaPedidoVpne(listaArq, idCliente, idDepartamento, nomeBD);

                    if (condicao.startsWith("ERRO")) {
                        response.sendRedirect("Cliente/Servicos/vpne.jsp?msg=" + condicao);
                    } else {
                        response.sendRedirect("Cliente/Servicos/vpne.jsp?msg=" + condicao);
                    }
                }

            } catch (FileUploadException ex) {
                response.sendRedirect("Cliente/Servicos/vpne.jsp?msg=Falha na importacao!\n" + ex);
            } catch (Exception ex) {
                response.sendRedirect("Cliente/Servicos/vpne.jsp?msg=Falha na importacao!\n" + ex);
            }

        } else {
            response.sendRedirect("Cliente/Servicos/vpne.jsp?msg=is not a multipart form");
        }
    } else {
        response.sendRedirect("Cliente/Servicos/vpne.jsp?msg=Sua sessao expirou!");
    }
}

From source file:com.tryAndFitV1.servlet.image.DoUploadImage.java

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

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

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();
                    System.out.println("filrpath1: " + name);
                    file = new File(UPLOAD_DIRECTORY + File.separator + name);
                    item.write(file);
                    System.out.println("filrpath: " + UPLOAD_DIRECTORY + File.separator + name);
                }
            }

            //File uploaded successfully
            request.setAttribute("message1", "Fichier tlcharg avec succs");
            String msg = file.getAbsolutePath();
            System.err.println("fichier tlcharg : " + msg);
            request.setAttribute("message2", file.getAbsolutePath());
        } catch (Exception ex) {
            request.setAttribute("message", "Echec " + ex);
        }

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

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

From source file:datalab.upo.ladonspark.controller.uploadFile.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  w  w  .j a v a  2  s .  c o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, Exception {
    List<objectresult> lor = new ArrayList<>();
    List<objectresult> loraux = new ArrayList<>();
    boolean result = false;
    String urlf = "";
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    // req es la HttpServletRequest que recibimos del formulario.
    // Los items obtenidos sern cada uno de los campos del formulario,
    // tanto campos normales como ficheros subidos.
    List items = upload.parseRequest(request);

    // Se recorren todos los items, que son de tipo FileItem
    for (Object item : items) {
        FileItem uploaded = (FileItem) item;

        // Hay que comprobar si es un campo de formulario. Si no lo es, se guarda el fichero
        // subido donde nos interese
        if (!uploaded.isFormField()) {
            // No es campo de formulario, guardamos el fichero en algn sitio
            if (!uploaded.getName().equals("")) {
                urlf = uploaded.getName();
                File fichero = new File(this.getPath() + "src/main/webapp/algorithm/dataAlgoritm/",
                        uploaded.getName());
                uploaded.write(fichero);
            } else {
                result = true;
            }
        } else {
            // es un campo de formulario, podemos obtener clave y valor
            String key = uploaded.getFieldName();
            String value = uploaded.getString();
            lor.add(new objectresult(key, value));
            if (value == null || value.equals("")) {
                result = true;

            }
        }
    }

    if (result) {
        request.getSession().setAttribute("error", "error");
        String url = "algorithm/addalgo.jsp";
        response.sendRedirect(url);
    } else {
        Algorithm a = new Algorithm(lor.get(0).getValue(), lor.get(1).getValue(), urlf);
        DaoAlgoritm da = new DaoAlgoritm();
        da.create(a);
        a = da.getAlgoritm(a.getNameAlg());
        DaoParameter dp = new DaoParameter();
        for (int i = 3; i < lor.size(); i++) {
            dp.create(new Parameter(a, lor.get(i).getValue(), lor.get(i + 1).getValue()));
            i++;
        }

        request.getSession().setAttribute("algorithm", new DaoAlgoritm().optenerAlgoritmos());
        String url = "algorithm/masteralgo.jsp";
        response.sendRedirect(url);
    }
}

From source file:calliope.handler.post.AeseStripHandler.java

/**
 * Strip an xml document into markup and plain text
 * @param request the original request object
 * @return a MIM multipart encoded response
 * @throws AeseException //from  www.  j  a v a 2s.  c o m
 */
String stripDocument(HttpServletRequest request) throws AeseException {
    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        String format = Formats.STIL;
        String style = Formats.DEFAULT;
        String recipe = null;
        String xml = null;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            String name = item.getFieldName();
            if (name.equals(Params.STYLE))
                style = item.getString();
            else if (name.equals(Params.FORMAT))
                format = item.getString();
            else if (name.equals(Params.RECIPE))
                recipe = item.getString();
            else if (name.equals(Params.XML))
                xml = item.getString();
        }
        if (xml != null) {
            JSONResponse markup = new JSONResponse(JSONResponse.STIL);
            JSONResponse text = new JSONResponse(JSONResponse.TEXT);
            AeseStripper stripper = new AeseStripper();
            int res = stripper.strip(xml, recipe, style, "en_GB", null, Utils.isHtml(xml), text, markup);
            if (res == 1) {
                Multipart mime = new Multipart();
                mime.putTextParam(format, markup.getBody(), MIMETypes.JSON);
                mime.putTextParam(Formats.TEXT, text.getBody(), MIMETypes.TEXT);
                return mime.toString();
            }
        }
        throw new ParamException("invalid parameters for strip");
    } catch (Exception e) {
        throw new AeseException(e);
    }
}

From source file:com.eufar.asmm.server.UploadImage.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("UploadImage - the function started");
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(MAX_MEMORY_SIZE);
    String uploadFolder = getServletContext().getRealPath("") + DATA_DIRECTORY;
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(MAX_REQUEST_SIZE);
    double maxSize = (MAX_REQUEST_SIZE / 1024) / 1024;
    System.out.println("UploadImage - max image size: " + maxSize + " Mbytes");
    try {//w  w  w.ja  v a2 s . c om
        @SuppressWarnings("rawtypes")
        List items = upload.parseRequest(request);
        @SuppressWarnings("rawtypes")
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            Object obj = iter.next();
            org.apache.commons.fileupload.FileItem item = (org.apache.commons.fileupload.FileItem) obj;
            String fileExt = FilenameUtils.getExtension(item.getName());
            if (fileExt.matches("(jpg|jpeg|bmp|png|JPG|JPEG|BMP|PNG)")) {
                System.out.println("UploadImage - image accepted");
                if (!item.isFormField()) {
                    File uploadedFile = File.createTempFile("tmp_", "." + fileExt, new File(uploadFolder));
                    item.write(uploadedFile);
                    double fileSize = item.getSize();
                    fileSize = (fileSize / 1024) / 1024;
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("text/html");
                    response.getWriter().write(uploadedFile.getName());
                    System.out.println("UploadImage - " + uploadedFile.getPath() + ": upload ok...");
                    System.out.println("UploadImage - " + uploadedFile.getPath() + ": " + fileSize + " MBytes");
                    if (new File(uploadedFile.getPath()).isFile()) {
                        System.out.println("PrintFunction - picture (webapps): the file exists.");
                    } else {
                        System.out.println("PrintFunction - picture (webapps): the file doesn't exist.");
                    }
                    if (new File(uploadedFile.getPath()).isFile()) {
                        System.out.println("PrintFunction - picture (webapps): the file can be read.");
                    } else {
                        System.out.println("PrintFunction - picture (webapps): the file can't be read.");
                    }
                } else {
                    System.out.println("UploadImage - a problem occured with the file format");
                }
            } else {
                System.out.println("UploadImage - image rejected: wrong format");
                response.setCharacterEncoding("UTF-8");
                response.setContentType("text/html");
                response.getWriter().write("format");
            }
        }
    } catch (Exception ex) {
        System.out.println("UploadImage - a problem occured: " + ex);
        response.getWriter().write("ERROR:" + ex.getMessage());
    }
}

From source file:com.app.uploads.ImageUploads.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w  w w.j a v a 2  s  .c  o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String[] Fielname = new String[2];
    CallableStatement pro;
    int i = 0;
    String UPLOAD_DIRECTORY = getServletContext().getRealPath("\\uploads\\");
    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                String name = "";
                List<FileItem> multiparts;
                multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

                for (FileItem item : multiparts) {
                    if (!item.isFormField()) {
                        name = new File(item.getName()).getName();
                        item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
                    } else if (item.isFormField()) {
                        String fiel = item.getFieldName();
                        InputStream is = item.getInputStream();
                        byte[] b = new byte[is.available()];
                        is.read(b);
                        if (i == 0) {
                            Fielname[0] = new String(b);
                        } else {
                            Fielname[1] = new String(b);
                        }
                        i++;
                    }

                }

                //File uploaded successfully
                Connection connect = OracleConnect.getConnect(Dir.Host, Dir.Port, Dir.Service, Dir.UserName,
                        Dir.PassWord);
                pro = connect.prepareCall("{call STILL_INSERT(?,?,?)}");
                pro.setString(1, name);
                pro.setString(2, Fielname[0]);
                pro.setString(3, Fielname[1]);
                pro.executeQuery();
                pro.close();
                connect.close();
                request.setAttribute("message", "File Uploaded Successfully");
                request.setAttribute("name", name);
            } catch (Exception ex) {
                request.setAttribute("message", "File Upload Failed due to " + ex);
            }

        } else {
            request.setAttribute("message", "Sorry this Servlet only handles file upload request");
        }
        out.print("Description:" + Fielname[0]);
        out.print("Locator:" + Fielname[1]);
        String pathReal = getServletContext().getRealPath("\\uploads\\");
        request.setAttribute("Description", Fielname[0]);
        request.setAttribute("Locator", Fielname[1]);
        request.setAttribute("path", pathReal);
        request.getRequestDispatcher("/result.jsp").forward(request, response);
    } finally {
        out.close();
    }
}

From source file:com.assignment.elance.controller.FileUploadServlet.java

/**
 * Upon receiving file upload submission, parses the request to read upload
 * data and saves the file on disk./*from   w ww .  j  a v  a 2 s .  c o m*/
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // checks if the request actually contains upload file
    if (!ServletFileUpload.isMultipartContent(request)) {
        // if not, we stop here
        PrintWriter writer = response.getWriter();
        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 = getServletContext().getRealPath("") + File.separator
            + SystemAttributes.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
            for (FileItem item : formItems) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String file = randomFileNameGenerator();
                    String filePath = uploadPath + File.separator + file;
                    File storeFile = new File(filePath);

                    // saves the file on disk
                    item.write(storeFile);
                    FilesManager fm = new FilesManager();
                    boolean send_dir = false;
                    switch (Integer.parseInt(request.getParameter("senddir"))) {
                    case 0:
                        send_dir = false;
                        break;
                    case 1:
                        send_dir = true;
                        break;
                    }
                    fm.insert(fileName, file, Integer.parseInt(request.getParameter("jobId")), send_dir);
                    request.setAttribute("message", "Upload has been done successfully!");
                }
            }
        }
    } catch (Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }
    //        // redirects client to message page
    //        getServletContext().getRequestDispatcher("/message.jsp").forward(
    //                request, response);
    switch (Integer.parseInt(request.getParameter("callbackpage"))) {
    case 0:
        response.sendRedirect("projectOverview.jsp?pId=" + Integer.parseInt(request.getParameter("jobId")));
        break;
    case 1:
        response.sendRedirect("project.jsp?jobId=" + Integer.parseInt(request.getParameter("jobId")));
        break;

    }
}

From source file:com.bid.online.presentation.bidmanagement.UploadFile.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w  ww. java  2 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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    String url = "";
    FileItem item = null;
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List items = upload.parseRequest(request);
            Iterator it = items.iterator();

            while (it.hasNext()) {
                item = (FileItem) it.next();
                if (!item.isFormField()) {
                    String fileName = item.getName();
                    String root = getServletContext().getRealPath("/");
                    File path = new File(root + "/uploads");
                    if (!path.exists()) {
                        boolean status = path.mkdir();
                    }
                    File uploadedFile = new File(path + "/" + fileName);
                    //System.out.println(uploadedFile.getAbsolutePath());
                    url = "uploads" + "/" + fileName;
                    item.write(uploadedFile);
                }
            }

        } catch (FileUploadException e) {

        } catch (Exception e) {

        }
        Gson gson = new Gson();
        JsonObject jResponse = new JsonObject();
        if (item != null) {
            Image img = new Image();
            img.setName(item.getName());
            img.setUrl(url);
            img = bidService.createImage(img);

            ImageView imgView = new ImageView();
            imgView.setId(String.valueOf(img.getId()));
            imgView.setName(item.getName());
            imgView.setUrl(url);
            JsonElement imgJason = gson.toJsonTree(imgView);
            jResponse.addProperty("success", Boolean.TRUE);
            jResponse.add("img", imgJason);
        } else {
            jResponse.addProperty("success", Boolean.FALSE);
        }
        PrintWriter out = response.getWriter();
        response.setContentType("text/html");
        response.setHeader("Cache-control", "no-cache, no-store");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "-1");

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setHeader("Access-Control-Max-Age", "86400");
        System.out.println(jResponse.toString());
        out.println(jResponse.toString());
        out.close();
    }
}

From source file:com.recipes.controller.Recipes.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  ww  w . j a  va 2 s .  c o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    DAO dao = new DAO();
    HttpSession session = request.getSession(true);
    if (request.getParameter("add") != null) {
        response.sendRedirect("addRecipe.jsp");
    } else if (request.getParameter("insert") != null) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> fields = upload.parseRequest(request);

            Iterator<FileItem> it = fields.iterator();
            if (!it.hasNext()) {
                // fayl yoxdur mesaj
                return;
            }

            String title = "";//String deyiwenleri gotururuy
            String article = "";
            String category = "";
            String prepareRules = "";
            String image = "";
            List<String> composition = new ArrayList<>();
            String cook_time = "";
            String total_time = "";
            String prep_time = "";

            while (it.hasNext()) { // eger file varsa
                FileItem fileItem = it.next(); // iteratorun next metodu cagrilir
                boolean isFormField = fileItem.isFormField(); // isformField-input yoxlanilirki 
                if (isFormField) { // eger isFormFIelddise
                    switch (fileItem.getFieldName()) {
                    case "title":
                        title = fileItem.getString("UTF-8").trim();
                        break;
                    case "category":
                        category = fileItem.getString("UTF-8").trim();
                        break;
                    case "article":
                        article = fileItem.getString("UTF-8").trim();
                        break;
                    case "prepareRules":
                        prepareRules = fileItem.getString("UTF-8").trim();
                        break;
                    case "image":
                        image = fileItem.getString("UTF-8").trim();
                        break;
                    case "tags":
                        composition.add(fileItem.getString("UTF-8").trim());
                        break;
                    case "prep_time":
                        prep_time = fileItem.getString("UTF-8").trim();
                        break;
                    case "cook_time":
                        cook_time = fileItem.getString("UTF-8").trim();
                        break;
                    case "total_time":
                        total_time = fileItem.getString("UTF-8").trim();
                        break;
                    }
                } else {
                    if (fileItem.getFieldName().equals("image")) {
                        if (!fileItem.getString("UTF-8").trim().equals("")) {
                            image = fileItem.getName();
                            image = dao.generateCode() + image;
                            String relativeWebPath = "photos";
                            String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
                            File file = new File(absoluteDiskPath + "/", image);
                            fileItem.write(file);
                        }
                    }
                }
            }

            Recipe recipe = new Recipe();
            recipe.setArticle(article);
            recipe.setCategory(category);
            String comps = "";
            for (String c : composition)
                comps += c + ",";
            if (comps.contains(","))
                comps = comps.substring(0, comps.length() - 1);
            recipe.setComposition(comps);
            if (image.isEmpty()) {
                image = "defaultrecipe.jpg";
            }
            recipe.setImage(image);
            recipe.setLike_count(0);
            recipe.setPrepared_rules(prepareRules);
            recipe.setTitle(title);
            recipe.setUser_id(Integer.parseInt(session.getAttribute("user_id").toString()));
            recipe.setVisible(1);
            recipe.setPrep_time(prep_time);
            recipe.setCook_time(cook_time);
            recipe.setTotal_time(total_time);
            dao.insertRecipe(recipe);
            response.sendRedirect("addRecipe.jsp?success=");
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }

    } else if (request.getParameter("id") != null) {
        response.sendRedirect("recipeDetails.jsp?id=" + request.getParameter("id"));
    }

    else {
        response.sendRedirect("index.jsp");
    }

}

From source file:hd.controller.AddImageToProductServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w w w. j  a va2 s  .  c  o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) { //to do

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

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

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

                } else if (!item.isFormField()) {
                    try {
                        long time = System.currentTimeMillis();
                        String itemName = item.getName();
                        fileName = time + itemName.substring(itemName.lastIndexOf("\\") + 1);
                        String RealPath = getServletContext().getRealPath("/") + "images\\" + fileName;
                        File savedFile = new File(RealPath);
                        item.write(savedFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
            String productID = (String) params.get("txtProductId");
            System.out.println(productID);
            String tilte = (String) params.get("newGalleryName");
            String description = (String) params.get("GalleryDescription");
            String url = "images/" + fileName;
            ProductDAO productDao = new ProductDAO();
            ProductPhoto productPhoto = productDao.insertProductPhoto(tilte, description, url, productID);

            response.sendRedirect("MyProductDetailServlet?action=showDetail&txtProductID=" + productID);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        out.close();
    }
}