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:com.kk.dic.action.Upload.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    out = response.getWriter();/*from   w ww  .  j  a va  2 s.  co m*/
    Connection con;
    PreparedStatement pstm = null;
    String fname = "";
    String keyword = "";
    String cd = "";
    String a = (String) request.getSession().getAttribute("email");
    System.out.println("User Name : " + a);
    try {
        boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
        if (!isMultipartContent) {
            return;
        }
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        out.print("one");
        try {
            List<FileItem> fields = upload.parseRequest(request);
            Iterator<FileItem> it = fields.iterator();
            if (!it.hasNext()) {
                return;
            }

            while (it.hasNext()) {
                FileItem fileItem = it.next();
                if (fileItem.getFieldName().equals("name")) {
                    fname = fileItem.getString();
                    System.out.println("File Name" + fname);
                } else if (fileItem.getFieldName().equals("keyword")) {
                    keyword = fileItem.getString();
                    System.out.println("File Keyword" + keyword);
                } else {

                }
                boolean isFormField = fileItem.isFormField();
                if (isFormField) {
                } else {
                    out.print("one");
                    try {
                        con = Dbconnection.getConnection();
                        pstm = con.prepareStatement(
                                "insert into files (file, keyword, filetype, filename, CDate, owner, size, data, frank, file_key)values(?,?,?,?,?,?,?,?,?,?)");
                        out.println("getD " + fileItem.getName());
                        String str = getStringFromInputStream(fileItem.getInputStream());
                        // secretkey generating
                        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
                        keyGen.init(128);
                        SecretKey secretKey = keyGen.generateKey();
                        System.out.println("secret key:" + secretKey);
                        //converting secretkey to String
                        byte[] be = secretKey.getEncoded();//encoding secretkey
                        String skey = Base64.encode(be);
                        System.out.println("converted secretkey to string:" + skey);
                        String cipher = new encryption().encrypt(str, secretKey);
                        System.out.println(str);
                        //for get extension from given file
                        String b = fileItem.getName().substring(fileItem.getName().lastIndexOf('.'));
                        System.out.println("File Extension" + b);
                        pstm.setBinaryStream(1, fileItem.getInputStream());
                        pstm.setString(2, keyword);
                        pstm.setString(3, b);
                        pstm.setString(4, fname);
                        pstm.setDate(5, getCurrentDate());
                        pstm.setString(6, a);
                        pstm.setLong(7, fileItem.getSize());
                        pstm.setString(8, cipher);
                        pstm.setString(9, "0");
                        pstm.setString(10, skey);
                        /*Cloud Start*/
                        File f = new File("D:/" + fileItem.getName());
                        out.print("<br/>" + f.getName());
                        FileWriter fw = new FileWriter(f);
                        fw.write(cipher);
                        fw.close();
                        Ftpcon ftpcon = new Ftpcon();
                        ftpcon.upload(f, fname);
                        /*Cloud End*/
                        int i = pstm.executeUpdate();
                        if (i == 1) {
                            response.sendRedirect("upload.jsp?msg=success");
                        } else {
                            response.sendRedirect("upload.jsp?msgg=failed");
                        }
                        con.close();
                    } catch (Exception e) {
                        out.println(e);
                    }
                }
            }
        } catch (Exception ex) {
            out.print(ex);
            Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
        }
    } finally {
        out.close();
    }
}

From source file:eml.studio.server.file.FileUploadServlet.java

/**
 * save file upload to server//from   w w w.  j ava  2 s . co  m
 * @param request HttpServletRequest
 * @param response HttpServletResponse
 * @throws ServletException
 */

public void saveUploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    List items = null;
    List items_findId = null;
    try {
        items = upload.parseRequest(request);
        items_findId = items;
    } catch (FileUploadException ex) {
        ex.printStackTrace();
    }
    String ID = new String();
    Iterator iter_findId = items_findId.iterator();
    while (iter_findId.hasNext()) {
        FileItem item_findId = (FileItem) iter_findId.next();
        if (item_findId.isFormField()) {
            String fieldName = item_findId.getFieldName();
            String fieldValue;
            try {
                fieldValue = item_findId.getString("UTF-8");

                if ("Fileuuid".equals(fieldName)) {
                    ID = Constants.MODULE_PATH + "/" + fieldValue;

                } else
                    ID = Constants.DATASET_PATH + "/" + fieldValue;
                logger.info("[UUID]:" + fieldName + ":" + ID);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        if (item.isFormField()) {
        } else {
            InputStream in;
            try {
                in = item.getInputStream();
                if (item.getName().endsWith(".zip")) {
                    unZipFiles(in, ID);
                    HDFSIO.uploadfile("/" + ID + "/", item, item.getName());
                } else {
                    if (ID.contains("Data")) {
                        HDFSIO.uploadfile("/" + ID + "/", item, ID.split("Data")[1]);
                    } else
                        HDFSIO.uploadfile("/" + ID + "/", item, item.getName());
                }

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}

From source file:controller.StudentController.java

@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addorchange(HttpServletRequest request) {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    // int mssv = Integer.parseInt(request.getParameter("mssv"));
    // String tensv = request.getParameter("tensv");
    // String ngaysinh = request.getParameter("ngaysinh");
    // String ngaydi = request.getParameter("ngaydi");
    // String que = request.getParameter("que");
    // String lop = request.getParameter("lop");
    // String khoa = request.getParameter("khoa");
    // int sdt = Integer.parseInt(request.getParameter("sdt"));
    // int maphong = Integer.parseInt(request.getParameter("roomnum"));
    // int makhu = Integer.parseInt(request.getParameter("roomregion"));

    int mssv = 0;
    String tensv = null;/*from w w  w .  j a v  a  2  s .co  m*/
    String ngaysinh = null;
    String ngaydi = null;
    String que = null;
    String lop = null;
    String khoa = null;
    int sdt = 0;
    int maphong = 0;
    int makhu = 0;
    FileItem f = null;
    String fName = null;
    try {
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.getFieldName().equals("mssv")) {
                mssv = Integer.parseInt(item.getString());
            }

            if (item.getFieldName().equals("tensv")) {
                tensv = item.getString();
            }
            if (item.getFieldName().equals("ngaysinh")) {
                ngaysinh = item.getString();
            }
            if (item.getFieldName().equals("ngaydi")) {
                ngaydi = item.getString();
            }
            if (item.getFieldName().equals("que")) {
                que = item.getString();
            }
            if (item.getFieldName().equals("lop")) {
                lop = item.getString();
            }
            if (item.getFieldName().equals("khoa")) {
                khoa = item.getString();
            }
            if (item.getFieldName().equals("sdt")) {
                sdt = Integer.parseInt(item.getString());
            }
            if (item.getFieldName().equals("roomnum")) {
                maphong = Integer.parseInt(item.getString());
            }
            if (item.getFieldName().equals("roomregion")) {
                makhu = Integer.parseInt(item.getString());
            }

            if (!item.isFormField()) {
                f = item;
                fName = new File(item.getName()).getName();

            }
        }

    } catch (FileUploadException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    RoomRegion region = new RoomRegion(makhu, "");
    Room room = new Room(maphong, region, 0, 0, null, null);
    if (room.checkRoom()) {
        Student student = new Student(mssv, tensv, ngaysinh, que, lop, khoa, room, sdt, ngaydi, fName);
        request.setAttribute("roomnum", new Room().roomList());
        request.setAttribute("roomregion", new RoomRegion().regionList());
        try {
            if (student.add() >= 3) {
                String path = request.getServletContext().getRealPath("/");
                String UPLOAD_DIRECTORY = path + "/static/uploads";
                File dir = new File(UPLOAD_DIRECTORY);
                dir.mkdirs();
                File file = new File(dir.getAbsolutePath() + System.getProperty("file.separator") + fName);

                f.write(file);
                System.out.println(file.getPath());
                request.setAttribute("message", "Thm thnh cng!");
            } else {
                request.setAttribute("message", "Khng thm c, Sinh vin ny  tn ti!");
            }
        } catch (SQLException ex) {
            Logger.getLogger(StudentController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        request.setAttribute("message", "Phng ny hin  y!");
    }
    request.setAttribute("id", "add");
    return SVManager(request);
}

From source file:edu.lafayette.metadb.web.controlledvocab.UpdateVocab.java

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*///www  . j  a v a2 s .  c  o m
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    PrintWriter out = response.getWriter();
    String vocabName = null;
    String name = "nothing";
    String status = "Upload failed ";

    try {

        if (ServletFileUpload.isMultipartContent(request)) {
            status = "isMultiPart";
            ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
            List fileItemsList = servletFileUpload.parseRequest(request);
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */

            InputStream input = null;
            Iterator it = fileItemsList.iterator();
            String result = "";
            String vocabs = null;
            int assigned = -1;

            while (it.hasNext()) {
                FileItem fileItem = (FileItem) it.next();
                result += "UpdateVocab: Form Field: " + fileItem.isFormField() + " Field name: "
                        + fileItem.getFieldName() + " Name: " + fileItem.getName() + " String: "
                        + fileItem.getString("utf-8") + "\n";
                if (fileItem.isFormField()) {
                    /* The file item contains a simple name-value pair of a form field */
                    if (fileItem.getFieldName().equals("vocab-name"))
                        vocabName = fileItem.getString();
                    else if (fileItem.getFieldName().equals("vocab-terms"))
                        vocabs = fileItem.getString("utf-8");
                    else if (fileItem.getFieldName().equals("assigned-field"))
                        assigned = Integer.parseInt(fileItem.getString());
                } else {
                    if (fileItem.getString() != null && !fileItem.getString().equals("")) {
                        @SuppressWarnings("unused")
                        String content = "nothing";
                        /* The file item contains an uploaded file */

                        /* Create new File object
                        File uploadedFile = new File("test.txt");
                        if(!uploadedFile.exists())
                           uploadedFile.createNewFile();
                        // Write the uploaded file to the system
                        fileItem.write(uploadedFile);
                        */
                        name = fileItem.getName();
                        content = fileItem.getContentType();
                        input = fileItem.getInputStream();
                    }
                }
            }
            //MetaDbHelper.note(result);
            if (vocabName != null) {
                Set<String> vocabList = new TreeSet<String>();
                if (input != null) {
                    Scanner fileSc = new Scanner(input);
                    while (fileSc.hasNextLine()) {
                        String vocabEntry = fileSc.nextLine();
                        vocabList.add(vocabEntry.trim());
                    }

                    HttpSession session = request.getSession(false);
                    if (session != null) {
                        String userName = (String) session.getAttribute("username");
                        SysLogDAO.log(userName, Global.SYSLOG_PROJECT,
                                "User " + userName + " created vocab " + vocabName);
                    }
                    status = "Vocab name: " + vocabName + ". File name: " + name + "\n";

                } else {
                    //MetaDbHelper.note(vocabs);
                    for (String vocabTerm : vocabs.split("\n"))
                        vocabList.add(vocabTerm);
                }
                if (!vocabList.isEmpty()) {
                    boolean updated = ControlledVocabDAO.addControlledVocab(vocabName, vocabList)
                            || ControlledVocabDAO.updateControlledVocab(vocabName, vocabList);
                    if (updated) {
                        status = "Vocab " + vocabName + " updated successfully ";
                        if (assigned != -1)
                            if (!AdminDescAttributesDAO.setControlledVocab(assigned, vocabName)) {
                                status = "Vocab " + vocabName + " cannot be assigned to " + assigned;
                            }

                    } else
                        status = "Vocab " + vocabName + " cannot be updated/created";
                } else
                    status = "Vocab " + vocabName + " has empty vocabList";
            }
        }
    } catch (Exception e) {
        MetaDbHelper.logEvent(e);
    }
    MetaDbHelper.note(status);
    out.print(status);
    out.flush();
}

From source file:inet.common.jsf.request.FileUploadFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    boolean isMultipart = ServletFileUpload.isMultipartContent(httpServletRequest);

    if (isMultipart && !(request instanceof MultipartRequest)) {
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        if (thresholdSize != null) {
            diskFileItemFactory.setSizeThreshold(Integer.valueOf(thresholdSize));
        }/*from  ww  w.  ja va 2  s. co m*/
        if (uploadDir != null) {
            diskFileItemFactory.setRepository(new File(uploadDir));
        }

        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        MultipartRequest multipartRequest = new MultipartRequest(httpServletRequest, servletFileUpload);

        filterChain.doFilter(multipartRequest, response);
    } else {
        filterChain.doFilter(request, response);
    }
}

From source file:controller.insertProduct.java

private void insertProduct(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();

    String productType = null;/*  w ww  .j  a  v a2 s .  c  om*/
    String resolution = null;
    String hdmi = null;
    String usb = null;
    String model = null;
    String size = null;
    String warranty = null;

    String productName = null;
    int price = 0;
    String description = null;
    Integer quantity = null;
    String produceID = null;
    String image = null;

    String uploadDirectory = "/Product/Images";
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);
    File uploadDir;
    File storeFile;
    try {
        @SuppressWarnings("unchecked")
        List<FileItem> formItems = upload.parseRequest(request);
        if (formItems != null && formItems.size() > 0) {
            for (FileItem item : formItems) {
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadDirectory + File.separator + fileName;
                    storeFile = new File(filePath);
                    item.write(storeFile);
                    image = produceID + "/" + fileName;
                    System.out.println(storeFile.getPath());
                } else {
                    switch (item.getFieldName()) {
                    case "productName":
                        productName = item.getString("UTF-8");
                        break;
                    case "produceID": {
                        produceID = item.getString("UTF-8");
                        uploadDir = new File(uploadPath + uploadDirectory + "/" + produceID);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdir();
                        }
                        uploadDirectory = uploadPath + uploadDirectory + "/" + produceID;
                        break;
                    }
                    case "price":
                        price = (Integer.parseInt(item.getString("UTF-8")));
                        break;
                    case "quantity":
                        quantity = (Integer.parseInt(item.getString("UTF-8")));
                        break;
                    case "productType":
                        productType = item.getString("UTF-8");
                        break;
                    case "resolution":
                        resolution = item.getString("UTF-8");
                        break;
                    case "hdmi":
                        hdmi = item.getString("UTF-8");
                        break;
                    case "usb":
                        usb = item.getString("UTF-8");
                        break;
                    case "Model":
                        model = item.getString("UTF-8");
                        break;
                    case "size":
                        size = item.getString("UTF-8");
                        break;
                    case "warranty":
                        warranty = item.getString("UTF-8");
                        break;
                    case "description": {
                        description = item.getString("UTF-8");
                        System.out.println(description);
                        break;
                    }
                    }
                }
            }
        }
    } catch (Exception ex) {
        System.out.println(ex);
    }

    @SuppressWarnings("null")
    ProductInfo prinfo = new ProductInfo(productType, resolution, hdmi, usb, model, size, warranty);
    Products product = new Products(productName, price, description, quantity, image, prinfo, produceID);

    if (ProductsDAO.insertProduct(product)) {
        out.print(
                "<center><b><font color='red'>thm thnh cng! </font> <a href = './WEB/admin/showProduct.jsp'>quay v?</a></b></center>");
    } else {
        out.print(
                "<center><b><font color='red'>Thm tht bi! </font> <a href = './WEB/admin/showProduct.jsp'>quay v?</a></b></center>");
    }
}

From source file:Controller.ControllerImage.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* w  w w  . j av  a 2s  . c o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {

    } else {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (Exception 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());
            } else {

                try {
                    String itemName = item.getName();
                    fileName = itemName.substring(itemName.lastIndexOf("\\") + 1);
                    String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName;
                    String code = (String) params.get("txtCode");
                    String name = (String) params.get("txtName");
                    String price = (String) params.get("txtPrice");
                    int a = Integer.parseInt(price);
                    String image = (String) params.get("txtImage");
                    //Update  product
                    if (fileName.equals("")) {

                        Products sp = new Products();
                        sp.Update(code, name, price, image);
                        RequestDispatcher rd = request.getRequestDispatcher("product.jsp");
                        rd.forward(request, response);

                    } else {
                        // bat dau ghi file
                        File savedFile = new File(RealPath);
                        item.write(savedFile);
                        //ket thuc ghi
                        Products sp = new Products();
                        sp.Update(code, name, price, "upload\\" + fileName);

                        RequestDispatcher rd = request.getRequestDispatcher("product.jsp");
                        rd.forward(request, response);
                    }

                } catch (Exception e) {
                    RequestDispatcher rd = request.getRequestDispatcher("InformationError.jsp");
                    rd.forward(request, response);
                }
            }

        }
    }

    this.processRequest(request, response);

}

From source file:Control.HandleAddRestaurant.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w  ww  .  ja 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, FileUploadException, Exception {
    response.setContentType("text/html;charset=UTF-8");
    HttpSession session = request.getSession();
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        String path = getClass().getResource("/").getPath();
        String[] tempS = null;
        if (Paths.path == null) {
            File file = new File(path + "test.html");
            path = file.getParent();
            File file1 = new File(path + "test1.html");
            path = file1.getParent();
            File file2 = new File(path + "test1.html");
            path = file2.getParent();
            Paths.path = path;
        } else {
            path = Paths.path;
        }
        path = Paths.tempPath;
        Restaurant temp = new Restaurant();
        String name = null;
        String sepName = Tools.CurrentTime();
        if (ServletFileUpload.isMultipartContent(request)) {
            List<?> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            Iterator iter = multiparts.iterator();
            int index = 0;
            tempS = new String[multiparts.size() - 1];
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    name = new File(item.getName()).getName();

                    String FilePath = path + Paths.logoPathStore + sepName + name;
                    item.write(new File(FilePath));
                } else {
                    String test = item.getFieldName();
                    tempS[index++] = item.getString();
                }
            }
            index = 0;
            temp.ID = tempS[index++];
            temp.name = tempS[index++];
            temp.address = tempS[index++];
            temp.city = tempS[index++];
            temp.state = tempS[index++];
            temp.zipcode = tempS[index++];
            temp.email = tempS[index++];
            temp.phone = tempS[index++];
            temp.monHours = tempS[index++];
            temp.sunHours = tempS[index++];
            temp.minPrice = Double.parseDouble(tempS[index++]);
            temp.fee = Double.parseDouble(tempS[index++]);
            temp.type = Integer.parseInt(tempS[index++]);
            temp.logoImage = Paths.logoPath + sepName + name;
        }

        if (Restaurant.checkExisted(temp.ID, temp.name)) {

            response.sendRedirect("./Admin/AddRestaurant.jsp?index=1");
        } else {
            if (Restaurant.addNewRestaurant(temp)) {
                Tools.updateRestaurants(session);
                response.sendRedirect("./Admin/AddRestaurant.jsp?index=2");
            } else {
                response.sendRedirect("./Admin/AddRestaurant.jsp?index=3");
            }
        }

    } catch (Exception e) {
        response.sendRedirect("./Admin/AddRestaurant.jsp?index=0");
    }
}

From source file:admin.controller.ServletEditPersonality.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from ww 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
 */
@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 {

        uploadPath = AppConstants.BRAND_IMAGES_HOME;
        deletePath = 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(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("brandname")) {
                        brandname = fi.getString();
                    }
                    if (fieldName.equals("brandid")) {
                        brandid = fi.getString();
                    }
                    if (fieldName.equals("look")) {
                        lookid = fi.getString();
                    }

                    file_name_to_delete = brand.getFileName(Integer.parseInt(brandid));
                } else {
                    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 = brandname + "_" + Str + ".jpeg";
                    fileName = brandname + "_" + fileName;
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();

                    String file_path = uploadPath + File.separator + fileName;
                    String delete_path = deletePath + 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>");
                }
            }
            brand.editBrands(Integer.parseInt(brandid), brandname, Integer.parseInt(lookid), fileName);
            response.sendRedirect(request.getContextPath() + "/admin/brandpersonality.jsp");
            //                        request_dispatcher = request.getRequestDispatcher("/admin/looks.jsp");
            //                        request_dispatcher.forward(request, response);
            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 {
        out.close();
    }

}

From source file:controller.UpdateEC.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  ww  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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    ExtenuatingCircumstance ec = new ExtenuatingCircumstance();
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            String fname = StringUtils.EMPTY;
            String title = StringUtils.EMPTY;
            String desciption = StringUtils.EMPTY;
            String status = StringUtils.EMPTY;
            int id = 0;
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            ArrayList<FileItem> files = new ArrayList<>();
            for (FileItem item : multiparts) {
                if (item.isFormField()) {
                    if (item.getFieldName().equals("id")) {
                        id = Integer.parseInt(item.getString());
                        System.out.println("id: " + id);
                    }
                    if (item.getFieldName().equals("title")) {
                        title = item.getString();
                    }
                    if (item.getFieldName().equals("description")) {
                        desciption = item.getString();
                    }
                    if (item.getFieldName().equals("status")) {
                        status = item.getString();
                        System.out.println("status: " + status);
                    }

                } else {
                    if (StringUtils.isNotEmpty(item.getName())) {
                        files.add(item);
                    }
                }
            }

            HttpSession session = request.getSession(false);
            Account studentAccount = (Account) session.getAttribute("account");
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
            LocalDateTime now = LocalDateTime.now();

            // insert EC
            ec.setId(id);
            ec.setTitle(title);
            ec.setDescription(desciption);
            ec.setProcess_status(status);
            //ec.setSubmitted_date(now.toString());
            ec.setAccount(studentAccount.getId());

            new ExtenuatingCircumstanceDAO().updateEC(ec, "student");

            //insert additional evident evidence
            if (files.size() > 0) {
                insertedEvidence(files, now, ec, studentAccount);
            }

            request.setAttribute("resultMsg", "updated");
            request.getRequestDispatcher("AddNewECResult.jsp").forward(request, response);

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