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

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

Introduction

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

Prototype

public void setSizeThreshold(int sizeThreshold) 

Source Link

Document

Sets the size threshold beyond which files are written directly to disk.

Usage

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

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

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

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

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

    String message;

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

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

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

        // Process the uploaded file items

        for (FileItem fileItem : fileItems) {

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

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

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

From source file:kg12.Ex12_1.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  www.j  ava2  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();

    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:com.bluelotussoftware.apache.commons.fileupload.example.MultiContentServlet.java

/**
 * Handles the HTTP// w  ww.  j  a v  a 2s.  co m
 * <code>POST</code> method.
 *
 * @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
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter writer = null;
    InputStream is = null;
    FileOutputStream fos = null;

    try {
        writer = response.getWriter();
    } catch (IOException ex) {
        log(MultiContentServlet.class.getName() + "has thrown an exception: " + ex.getMessage());
    }

    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);

    if (isMultiPart) {
        log("Content-Type: " + request.getContentType());
        // Create a factory for disk-based file items
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

        /*
         * Set the file size limit in bytes. This should be set as an
         * initialization parameter
         */
        diskFileItemFactory.setSizeThreshold(1024 * 1024 * 10); //10MB.

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

        List items = null;

        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException ex) {
            log("Could not parse request", ex);
        }

        ListIterator li = items.listIterator();

        while (li.hasNext()) {
            FileItem fileItem = (FileItem) li.next();
            if (fileItem.isFormField()) {
                if (debug) {
                    processFormField(fileItem);
                }
            } else {
                writer.print(processUploadedFile(fileItem));
            }
        }
    }

    if ("application/octet-stream".equals(request.getContentType())) {
        log("Content-Type: " + request.getContentType());
        String filename = request.getHeader("X-File-Name");

        try {
            is = request.getInputStream();
            fos = new FileOutputStream(new File(realPath + filename));
            IOUtils.copy(is, fos);
            response.setStatus(HttpServletResponse.SC_OK);
            writer.print("{success: true}");
        } catch (FileNotFoundException ex) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            writer.print("{success: false}");
            log(MultiContentServlet.class.getName() + "has thrown an exception: " + ex.getMessage());
        } catch (IOException ex) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            writer.print("{success: false}");
            log(MultiContentServlet.class.getName() + "has thrown an exception: " + ex.getMessage());
        } finally {
            try {
                fos.close();
                is.close();
            } catch (IOException ignored) {
            }
        }

        writer.flush();
        writer.close();
    }
}

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

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from  w ww  . 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
 */
@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:com.bruce.gogo.utils.JakartaMultiPartRequest.java

/**
 * Creates a new request wrapper to handle multi-part data using methods adapted from Jason Pell's
 * multipart classes (see class description).
 *
 * @param saveDir        the directory to save off the file
 * @param servletRequest the request containing the multipart
 * @throws java.io.IOException  is thrown if encoding fails.
 *///from w  w w. j a  v a2 s. c o  m
public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException {
    DiskFileItemFactory fac = new DiskFileItemFactory();
    // Make sure that the data is written to file
    fac.setSizeThreshold(0);
    if (saveDir != null) {
        fac.setRepository(new File(saveDir));
    }

    // Parse the request
    try {
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setSizeMax(maxSize);
        ProgressListener myProgressListener = new MyProgressListener(servletRequest);
        upload.setProgressListener(myProgressListener);
        List items = upload.parseRequest(createRequestContext(servletRequest));

        for (Object item1 : items) {
            FileItem item = (FileItem) item1;
            if (LOG.isDebugEnabled())
                LOG.debug("Found item " + item.getFieldName());
            if (item.isFormField()) {
                LOG.debug("Item is a normal form field");
                List<String> values;
                if (params.get(item.getFieldName()) != null) {
                    values = params.get(item.getFieldName());
                } else {
                    values = new ArrayList<String>();
                }

                // note: see http://jira.opensymphony.com/browse/WW-633
                // basically, in some cases the charset may be null, so
                // we're just going to try to "other" method (no idea if this
                // will work)
                String charset = servletRequest.getCharacterEncoding();
                if (charset != null) {
                    values.add(item.getString(charset));
                } else {
                    values.add(item.getString());
                }
                params.put(item.getFieldName(), values);
            } else {
                LOG.debug("Item is a file upload");

                // Skip file uploads that don't have a file name - meaning that no file was selected.
                if (item.getName() == null || item.getName().trim().length() < 1) {
                    LOG.debug("No file has been uploaded for the field: " + item.getFieldName());
                    continue;
                }

                List<FileItem> values;
                if (files.get(item.getFieldName()) != null) {
                    values = files.get(item.getFieldName());
                } else {
                    values = new ArrayList<FileItem>();
                }

                values.add(item);
                files.put(item.getFieldName(), values);
            }
        }
    } catch (FileUploadException e) {
        LOG.error("Unable to parse request", e);
        errors.add(e.getMessage());
    }
}

From source file:com.intranet.intr.contabilidad.SupControllerGastos.java

@RequestMapping(value = "addGastoRF.htm", method = RequestMethod.POST)
public String addGastoRF_post(@ModelAttribute("ga") gastosR ga, BindingResult result,
        HttpServletRequest request) {/*from  ww  w .jav a  2s . com*/
    String mensaje = "";
    String ruta = "redirect:Gastos.htm";
    gastosR gr = new gastosR();
    //MultipartFile multipart = c.getArchivo();
    System.out.println("olaEnviarMAILS");
    String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\fotosfacturas";
    //File file=new File(ubicacionArchivo,multipart.getOriginalFilename());
    //String ubicacionArchivo="C:\\";
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024);

    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        List<FileItem> partes = upload.parseRequest(request);
        for (FileItem item : partes) {
            if (idPC != 0) {
                gr.setIdgasto(idPC);
                if (gastosRService.existe(item.getName()) == false) {
                    System.out.println("NOMBRE FOTO: " + item.getName());
                    File file = new File(ubicacionArchivo, item.getName());
                    item.write(file);
                    gr.setNombreimg(item.getName());
                    gastosRService.insertar(gr);
                }
            } else
                ruta = "redirect:Gastos.htm";
        }
        System.out.println("Archi subido correctamente");
    } catch (Exception ex) {
        System.out.println("Error al subir archivo" + ex.getMessage());
    }

    return ruta;

}

From source file:com.intranet.intr.contabilidad.SupControllerGastos.java

@RequestMapping(value = "updateGastoRF.htm", method = RequestMethod.POST)
public String EupdateGastoRF_post(@ModelAttribute("ga") gastosR ga, BindingResult result,
        HttpServletRequest request) {/*from   w w  w  .  ja  v a2s  .  c o  m*/
    String mensaje = "";
    String ruta = "redirect:Gastos.htm";

    //MultipartFile multipart = c.getArchivo();
    System.out.println("olaEnviarMAILS");
    String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\fotosfacturas";
    //File file=new File(ubicacionArchivo,multipart.getOriginalFilename());
    //String ubicacionArchivo="C:\\";
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024);

    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        List<FileItem> partes = upload.parseRequest(request);
        for (FileItem item : partes) {
            if (gr.getIdgasto() != 0) {

                if (gastosRService.existe(item.getName()) == false) {
                    System.out.println("updateeeNOMBRE FOTO: " + item.getName());
                    File file = new File(ubicacionArchivo, item.getName());
                    item.write(file);
                    gr.setNombreimg(item.getName());
                    gastosRService.updateGasto(gr);
                }
            } else
                ruta = "redirect:Gastos.htm";
        }
        System.out.println("Archi subido correctamente");
    } catch (Exception ex) {
        System.out.println("Error al subir archivo" + ex.getMessage());
    }

    return ruta;

}

From source file:UploadImageEdit.java

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

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

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

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

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

    ServletFileUpload upload = new ServletFileUpload(factory);

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

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

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

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

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

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

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

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

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

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

                }

            }
        }

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

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

}

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

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

    // ????//from  w w  w  .  ja  v  a 2 s.c om
    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);
    }
}

From source file:com.intranet.intr.proveedores.ProvController.java

@RequestMapping(value = "updateArchivos.htm", method = RequestMethod.POST)
public String updateArchivos_post(@ModelAttribute("provPresupAdj") prov_presup_adj provPresupAdj,
        BindingResult result, HttpServletRequest request) {
    String mensaje = "";

    try {//  w  ww.  j a v  a  2 s  .  com

        String ubicacionArchivo = "C:\\glassfish-4.1.1-web\\glassfish4\\glassfish\\domains\\domain1\\applications\\Intranet\\resources\\archivosProveedores";
        //File file=new File(ubicacionArchivo,multipart.getOriginalFilename());
        //String ubicacionArchivo="C:\\";

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024);
        ServletFileUpload upload = new ServletFileUpload(factory);

        List<FileItem> partes = upload.parseRequest(request);

        for (FileItem item : partes) {
            System.out.println("NOMBRE FOTO: " + item.getContentType());
            File file = new File(ubicacionArchivo, item.getName());

            item.write(file);
            prov_presup_adj pp = new prov_presup_adj();
            pp.setId_prov_presup(idPr);
            pp.setNombre(item.getName());
            pp.setTipo(item.getContentType());
            provPresupAdjService.Insert(pp);
        }
        //c.setImagenes(arc);

    } catch (Exception ex) {

    }
    return "redirect:updatePresupProv.htm?idP=" + idPr;

}