Example usage for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax.

Prototype

public void setSizeMax(long sizeMax) 

Source Link

Document

Sets the maximum allowed upload size.

Usage

From source file:cc.kune.core.server.manager.file.FileUploadManagerAbstract.java

@Override
@SuppressWarnings({ "rawtypes" })
protected void doPost(final HttpServletRequest req, final HttpServletResponse response)
        throws ServletException, IOException {

    beforePostStart();/* w  w  w .  j  a  va2 s .c  o  m*/

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

    if (!ServletFileUpload.isMultipartContent(req)) {
        LOG.warn("Not a multipart upload");
    }

    final ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum size before a FileUploadException will be thrown
    upload.setSizeMax(kuneProperties.getLong(KuneProperties.UPLOAD_MAX_FILE_SIZE) * 1024 * 1024);

    try {
        final List fileItems = upload.parseRequest(req);
        String userHash = null;
        StateToken stateToken = null;
        String typeId = null;
        String fileName = null;
        FileItem file = null;
        for (final Iterator iterator = fileItems.iterator(); iterator.hasNext();) {
            final FileItem item = (FileItem) iterator.next();
            if (item.isFormField()) {
                final String name = item.getFieldName();
                final String value = item.getString();
                LOG.info("name: " + name + " value: " + value);
                if (name.equals(FileConstants.HASH)) {
                    userHash = value;
                }
                if (name.equals(FileConstants.TOKEN)) {
                    stateToken = new StateToken(value);
                }
                if (name.equals(FileConstants.TYPE_ID)) {
                    typeId = value;
                }
            } else {
                fileName = item.getName();
                LOG.info("file: " + fileName + " fieldName: " + item.getFieldName() + " size: " + item.getSize()
                        + " typeId: " + typeId);
                file = item;
            }
        }
        createUploadedFile(userHash, stateToken, fileName, file, typeId);
        onSuccess(response);
    } catch (final FileUploadException e) {
        onFileUploadException(response);
    } catch (final Exception e) {
        onOtherException(response, e);
    }
}

From source file:com.javaweb.controller.SuaTinTucServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*from   w w w.  ja  v a 2 s  .co m*/
 * @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, ParseException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");

    //response.setCharacterEncoding("UTF-8");
    HttpSession session = request.getSession();
    String TieuDe = "", NoiDung = "", ngaydang = "", GhiChu = "", fileName = "";
    int idloaitin = 0, idTK = 0, idtt = 0;

    TintucService tintucservice = new TintucService();

    //File upload
    String folderupload = getServletContext().getInitParameter("file-upload");
    String rootPath = getServletContext().getRealPath("/");
    filePath = rootPath + folderupload;
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File("C:\\Windows\\Temp\\"));

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

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

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

        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters

                String fieldName = fi.getFieldName();
                fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();

                //change file name
                fileName = FileService.ChangeFileName(fileName);

                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + "/" + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }
                fi.write(file);
                //                    out.println("Uploaded Filename: " + fileName + "<br>");
            }

            if (fi.isFormField()) {
                if (fi.getFieldName().equalsIgnoreCase("TieuDe")) {
                    TieuDe = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("NoiDung")) {
                    NoiDung = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("NgayDang")) {
                    ngaydang = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("GhiChu")) {
                    GhiChu = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("loaitin")) {
                    idloaitin = Integer.parseInt(fi.getString("UTF-8"));
                } else if (fi.getFieldName().equalsIgnoreCase("idtaikhoan")) {
                    idTK = Integer.parseInt(fi.getString("UTF-8"));
                } else if (fi.getFieldName().equalsIgnoreCase("idtt")) {
                    idtt = Integer.parseInt(fi.getString("UTF-8"));
                }
            }
        }

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

    Date NgayDang = new SimpleDateFormat("yyyy-MM-dd").parse(ngaydang);

    Tintuc tt = tintucservice.GetTintucID(idtt);

    tt.setIdTaiKhoan(idTK);
    tt.setTieuDe(TieuDe);
    tt.setNoiDung(NoiDung);
    tt.setNgayDang(NgayDang);
    tt.setGhiChu(GhiChu);
    if (!fileName.equals("")) {
        if (tt.getImgLink() != null) {
            if (!tt.getImgLink().equals(fileName)) {
                tt.setImgLink(fileName);
            }
        } else {
            tt.setImgLink(fileName);
        }
    }

    boolean rs = tintucservice.InsertTintuc(tt);
    if (rs) {
        session.setAttribute("kiemtra", "1");
        response.sendRedirect("SuaTinTuc.jsp?idTintuc=" + idtt);
    } else {
        session.setAttribute("kiemtra", "0");
        response.sendRedirect("SuaTinTuc.jsp?idTintuc=" + idtt);
    }

    //        try (PrintWriter out = response.getWriter()) {
    //            /* TODO output your page here. You may use following sample code. */
    //            out.println("<!DOCTYPE html>");
    //            out.println("<html>");
    //            out.println("<head>");
    //            out.println("<title>Servlet SuaTinTucServlet</title>");            
    //            out.println("</head>");
    //            out.println("<body>");
    //            out.println("<h1>Servlet SuaTinTucServlet at " + request.getContextPath() + "</h1>");
    //            out.println("</body>");
    //            out.println("</html>");
    //        }
}

From source file:Ctrl.Upload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* ww w . java2s.  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 {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter writer = response.getWriter();

    try {

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

            writer.println("Error: Form must has enctype=multipart/form-data.");
            writer.flush();
            return;
        }
        // configures upload settings
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // sets memory threshold - beyond which files are stored in disk 
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // sets temporary location to store files
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);

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

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

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

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

        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 filePath = uploadPath + File.separator + fileName;

                    File storeFile = new File(filePath);
                    // saves the file on disk
                    item.write(storeFile);

                    request.setAttribute("ten", fileName);
                    request.setAttribute("msg", UPLOAD_DIRECTORY + "/" + fileName);
                    request.setAttribute("message",
                            "Upload has been done successfully >>" + UPLOAD_DIRECTORY + "/" + fileName);
                }
            }
        }

    } catch (Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }
    // redirects client to message page
    getServletContext().getRequestDispatcher("/Product.jsp").forward(request, response);

}

From source file:kg12.Ex12_1.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//ww w  .  j a  va2  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");
    PrintWriter out = response.getWriter();

    try {
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet Ex12_1</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>???</h1>");

        // multipart/form-data ??
        if (ServletFileUpload.isMultipartContent(request)) {
            out.println("???<br>");
        } else {
            out.println("?????<br>");
            out.close();
            return;
        }

        // ServletFileUpload??
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);

        // ???
        int fileSizeMax = 1024000;
        factory.setSizeThreshold(1024);
        sfu.setSizeMax(fileSizeMax);
        sfu.setHeaderEncoding("UTF-8");

        // ?
        String format = "%s:%s<br>%n";

        // ???????
        FileItemIterator fileIt = sfu.getItemIterator(request);

        while (fileIt.hasNext()) {
            FileItemStream item = fileIt.next();

            if (item.isFormField()) {
                //
                out.print("<br>??<br>");
                out.printf(format, "??", item.getFieldName());
                InputStream is = item.openStream();

                // ? byte ??
                byte[] b = new byte[255];

                // byte? b ????
                is.read(b, 0, b.length);

                // byte? b ? "UTF-8" ??String??? result ?
                String result = new String(b, "UTF-8");
                out.printf(format, "", result);
            } else {
                //
                out.print("<br>??<br>");
                out.printf(format, "??", item.getName());
            }
        }
        out.println("</body>");
        out.println("</html>");
    } catch (FileUploadException e) {
        out.println(e + "<br>");
        throw new ServletException(e);
    } catch (Exception e) {
        out.println(e + "<br>");
        throw new ServletException(e);
    } finally {
        out.close();
    }
}

From source file:edu.temple.cis3238.wiki.ui.servlets.UploaderServlet.java

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

        // 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 be  enctype = multipart/form-data.");
            writer.flush();
            setSuccess(false);
            return;
        }

        // configures upload settings
        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);
        if (request.getSession() != null && request.getSession().getAttribute("topicCollection") != null) {
            try {
                collection = (TopicCollection) request.getSession().getAttribute("topicCollection");
                setTopic(collection.getCurrentTopic());
                setTopicID(getTopic().getTopicID() + "");
            } catch (Exception e) {
                e.printStackTrace();
                if (getTopic() == null) {
                    try {
                        setTopicID(request.getSession().getAttribute("topicID").toString());
                        setTopic(new TopicVOBuilder().setTopicID(Integer.parseInt(getTopicID())).build());
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        } else {
            setTopicID("none");
        }

        String uploadPath = FileUtils.makeDir(getServletContext(), UPLOAD_DIRECTORY, getTopic());
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();

        }

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

            if (formItems != null && formItems.size() > 0) {
                // iterates over form's fields
                for (FileItem item : formItems) {

                    if (!item.isFormField()) {
                        fileName = new File(item.getName()).getName();
                        String filePath = uploadPath + File.separator + fileName;
                        System.out.println(filePath);
                        File storeFile = new File(filePath);

                        if (FileUtils.checkFileExtension(storeFile.getName().toLowerCase(), null)) {
                            item.write(storeFile);
                            request.setAttribute("sourceFile", fileName);
                            System.out.println("----------------------------");
                            System.out.println("FILENAME is :" + fileName);
                            System.out.println("----------------------------");
                            request.setAttribute("topicID", StringUtils.toS(getTopicID()));
                            setStatus(request, true, "Success: Topic " + StringUtils.toS(getTopicID())
                                    + " has saved file " + fileName + ". Upload has been done successfully!");
                        } else {
                            setStatus(request, false, "Exception: Invalid file extension");
                        }
                    }
                }
            } else {
                setStatus(request, false, "Exception: No valid file(s)");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            setStatus(request, false,
                    "Exception: " + StringUtils.coalesce(ex.getMessage(), ex.toString(), "unknown"));
        }
        // redirects client to message page
        getServletContext().getRequestDispatcher("/" + REDIRECT_ON_COMPLETE_PAGE).forward(request, response);
    }
}

From source file:com.krawler.br.spring.RConverterImpl.java

public Map convertWithFile(HttpServletRequest request, Map reqParams) throws ProcessException {
    HashMap itemMap = new HashMap(), tmpMap = new HashMap();
    try {//from  ww w . jav  a  2 s. c om
        FileItemFactory factory = new DiskFileItemFactory(4096, new File("/tmp"));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(1000000);
        List fileItems = upload.parseRequest(request);
        Iterator iter = fileItems.iterator();

        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            String key = item.getFieldName();
            OperationParameter o = (OperationParameter) reqParams.get(key);
            if (reqParams.containsKey(key)) {
                if (item.isFormField()) {
                    putItem(tmpMap, key,
                            getValue(item.getString("UTF-8"), mb.getModuleDefinition(o.getType())));
                } else {
                    File destDir = new File(StorageHandler.GetProfileImgStorePath());
                    if (!destDir.exists()) {
                        destDir.mkdirs();
                    }

                    File f = new File(destDir, UUID.randomUUID() + "_" + item.getName());
                    try {
                        item.write(f);
                    } catch (Exception ex) {
                        Logger.getLogger(RConverterImpl.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    putItem(tmpMap, key, f.getAbsolutePath());
                }
            }
        }

        iter = tmpMap.keySet().iterator();

        while (iter.hasNext()) {
            String key = (String) iter.next();
            OperationParameter o = (OperationParameter) reqParams.get(key);
            itemMap.put(key, convertToMultiType((List) tmpMap.get(key), o.getMulti(), o.getType()));
        }

    } catch (FileUploadException ex) {
        throw new ProcessException(ex.getMessage(), ex);
    } catch (UnsupportedEncodingException e) {
        throw new ProcessException(e.getMessage(), e);
    }
    return itemMap;
}

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

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

    boolean isMultipart;
    String filePath;//from ww w .j ava 2s . c  o m
    int maxFileSize = 9000 * 1024;
    int maxMemSize = 4 * 1024;
    File file;

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

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

    String message;

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File(this.getServletContext().getRealPath("/") + "img/"));

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

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

        // Process the uploaded file items

        for (FileItem fileItem : fileItems) {

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

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

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

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

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

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

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

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

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

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

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File(filePath));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);
            try {
                // Parse the request to get file items.
                List fileItems = upload.parseRequest(request);

                // Process the uploaded file items
                Iterator i = fileItems.iterator();
                while (i.hasNext()) {
                    FileItem fi = (FileItem) i.next();
                    if (!fi.isFormField()) {
                        // Get the uploaded file parameters
                        String fieldName = fi.getFieldName();

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

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

                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();
                        //  out.println("file size"+ sizeInBytes);
                        // Write the file
                        if (fileName.lastIndexOf("\\") >= 0) {
                            file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                        } else {
                            file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                        }
                        fi.write(file);
                        //  out.println("Uploaded Filename: " + filePath  + fileName + "<br />");
                        String savepath = filePath + fileName;

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

                        }

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

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

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

                        // media constructor

                        // response.redirect(listprojects.jsp);

                        processRequest(request, response);
                    }

                }

            }

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

From source file:application.controllers.admin.EditEmotion.java

private String uploadNewImage(HttpServletRequest request, HttpServletResponse response) {
    String linkImage = emotionSelected.linkImage;
    if (!ServletFileUpload.isMultipartContent(request)) {
        return "";
    }/*  ww w .j av a  2  s .c o  m*/
    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(UploadConstant.THRESHOLD_SIZE);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setFileSizeMax(UploadConstant.MAX_FILE_SIZE);
    upload.setSizeMax(UploadConstant.MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    //groupEmotionId chinh la folder chua
    // creates the directory if it does not exist
    String[] arrLink = emotionSelected.linkImage.split("/");
    if (arrLink.length < 3) {
        return "";
    }
    try {
        List formItems = upload.parseRequest(request);
        Iterator iter = formItems.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // processes only fields that are not form fields
            if (item.isFormField()) {
                //form field
                if (item.getFieldName().equals("groupEmotion")) {
                    try {
                        if (emotionSelected.groupEmotionId != Integer.parseInt(item.getString())) {
                            //thay doi group id --> chuyen file sang folder tuong ung va thay doi imagelink
                            //chuyen file sang folder tuong ung theo group da chon

                            String sourcePath = Registry.get("imageHost") + emotionSelected.linkImage;
                            //item.getString --> groupEmotion chon
                            String desPath = Registry.get("imageHost") + "/emotions-image/" + item.getString()
                                    + "/" + arrLink[3];

                            File sourceDir = new File(sourcePath);
                            File desDir = new File(desPath);
                            if (sourceDir.exists()) {
                                FileUtils.copyFile(sourceDir, desDir);
                                sourceDir.delete();

                            }

                            emotionSelected.groupEmotionId = Integer.parseInt(item.getString());
                            linkImage = "/emotions-image/" + emotionSelected.groupEmotionId + "/" + arrLink[3];

                        }
                    } catch (NumberFormatException ex) {
                        ex.printStackTrace();
                    }
                }
                if (item.getFieldName().equals("description")) {
                    emotionSelected.description = item.getString();
                }
                if (item.getFieldName().equals("imageURL")) {
                    emotionSelected.linkImage = item.getString();

                }
            } else {

                String fileName = new File(item.getName()).getName();
                //file name bang empty khi ko upload new image
                if ("".equals(fileName)) {
                    continue;
                }
                String filePath = Registry.get("imageHost") + emotionSelected.linkImage;
                File newImage = new File(filePath);
                File oldImage = new File(filePath);
                // xoa image cu bi edit
                if (oldImage.exists()) {
                    oldImage.delete();
                }
                // save image moi vao  folder cua group id va cung ten moi image cu
                item.write(newImage);

                //save lai file cua image moi
                linkImage = "/emotions-image/" + emotionSelected.groupEmotionId + "/" + arrLink[3];
            }
        }

    } catch (Exception ex) {
        Logger.getLogger(EditEmotion.class.getName()).log(Level.SEVERE, null, ex);
    }
    return linkImage;

}

From source file:jp.co.opentone.bsol.linkbinder.view.filter.UploadFileFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    // ????/*from w  ww . ja v a2  s . c o m*/
    if (!(req instanceof HttpServletRequest)) {
        chain.doFilter(req, res);
        return;
    }

    HttpServletRequest httpReq = (HttpServletRequest) req;
    // ??????????
    if (!ServletFileUpload.isMultipartContent(httpReq)) {
        chain.doFilter(req, res);
        return;
    }

    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload sfu = new ServletFileUpload(factory);

    factory.setSizeThreshold(thresholdSize);
    sfu.setSizeMax(maxSize); //
    sfu.setHeaderEncoding(req.getCharacterEncoding());

    try {
        @SuppressWarnings("unchecked")
        Iterator<FileItem> ite = sfu.parseRequest(httpReq).iterator();
        List<String> keys = new ArrayList<String>();
        List<String> names = new ArrayList<String>();
        List<String> fieldNames = new ArrayList<String>();
        List<Long> fileSize = new ArrayList<Long>();

        while (ite.hasNext()) {
            String name = null;
            FileItem item = ite.next();

            // ????
            if (!(item.isFormField())) {
                name = item.getName();
                name = name.substring(name.lastIndexOf('\\') + 1);
                if (StringUtils.isEmpty(name)) {
                    continue;
                }
                File f = null;
                // CHECKSTYLE:OFF
                // ??????????.
                while ((f = new File(createTempFilePath())).exists()) {
                }
                // CHECKSTYLE:ON
                if (!validateByteLength(name, maxFilenameLength, minFilenameLength)) {
                    // ????
                    names.add(name);
                    keys.add(UploadedFile.KEY_FILENAME_OVER);
                    fieldNames.add(item.getFieldName());
                    fileSize.add(item.getSize());
                } else if (item.getSize() == 0) {
                    // 0
                    names.add(name);
                    keys.add(UploadedFile.KEY_SIZE_ZERO);
                    fieldNames.add(item.getFieldName());
                    fileSize.add(item.getSize());
                } else if (maxFileSize > 0 && item.getSize() > maxFileSize) {
                    // ?
                    // ?0??????Validation
                    names.add(name);
                    keys.add(UploadedFile.KEY_SIZE_OVER);
                    fieldNames.add(item.getFieldName());
                    fileSize.add(item.getSize());
                } else {
                    item.write(f);
                    names.add(name);
                    keys.add(f.getName());
                    fieldNames.add(item.getFieldName());
                    fileSize.add(item.getSize());
                }
                f.deleteOnExit();
            }
        }

        // 
        UploadFileFilterResult result = new UploadFileFilterResult();
        result.setResult(UploadFileFilterResult.RESULT_OK);
        result.setNames(names.toArray(new String[names.size()]));
        result.setKeys(keys.toArray(new String[keys.size()]));
        result.setFieldNames(fieldNames.toArray(new String[fieldNames.size()]));
        result.setFileSize(fileSize.toArray(new Long[fileSize.size()]));
        writeResponse(req, res, result);
    } catch (Exception e) {
        e.printStackTrace();
        // 
        UploadFileFilterResult result = new UploadFileFilterResult();
        result.setResult(UploadFileFilterResult.RESULT_NG);
        writeResponse(req, res, result);
    }
}