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:com.raissi.utils.CustomFileUploadFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    if (bypass) {
        filterChain.doFilter(request, response);
        return;/*  ww w . j  a  v a  2s .  c  o  m*/
    }

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

    if (isMultipart) {
        logger.debug("Parsing file upload request");

        FileCleaningTracker fileCleaningTracker = FileCleanerCleanup
                .getFileCleaningTracker(request.getServletContext());
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        diskFileItemFactory.setFileCleaningTracker(fileCleaningTracker);
        if (thresholdSize != null) {
            diskFileItemFactory.setSizeThreshold(Integer.valueOf(thresholdSize));
        }
        if (uploadDir != null) {
            diskFileItemFactory.setRepository(new File(uploadDir));
        }

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

        logger.debug(
                "File upload request parsed succesfully, continuing with filter chain with a wrapped multipart request");

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

From source file:com.wakasta.tubes2.AddProductPost.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String item_data = "";
    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
        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>");
        return;//from  w  w  w . jav a2 s  .  c o  m
    }
    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:\\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();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // 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));
                }

                item_data = Base64.encodeBase64String(fi.get());

                fi.write(file);

                //                    out.println("Uploaded Filename: " + fileName + "<br>");
                //                    out.println(file);
            }
        }
        out.println("</body>");
        out.println("</html>");
    } catch (FileUploadException ex) {
        Logger.getLogger(AddProductPost.class.getName()).log(Level.SEVERE, null, ex);
    } catch (java.lang.Exception ex) {
        Logger.getLogger(AddProductPost.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:controllers.ServerController.java

public void uploadFile(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    String UPLOAD_DIRECTORY = "/opt/ppd";
    int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
    int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
    int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);

    File uploadDir = new File(UPLOAD_DIRECTORY);
    if (!uploadDir.exists())
        uploadDir.mkdir();//from  w w w  . j  a va 2s .  co  m

    try {
        // parses the request's content to extract file data
        @SuppressWarnings("unchecked")
        List<FileItem> formItems = upload.parseRequest(request);
        if (formItems != null && formItems.size() > 0) {
            // iterates over form's fields
            for (FileItem item : formItems) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = UPLOAD_DIRECTORY + File.separator + fileName;
                    File storeFile = new File(filePath);
                    item.write(storeFile);
                    PrintWriter out = response.getWriter();
                    Runtime runtime = Runtime.getRuntime();
                    Process process = runtime.exec("/opt/script.sh " + fileName);
                    out.write("uplad success");
                    out.close();
                }
            }
        }
    } catch (Exception ex) {
        PrintWriter out = response.getWriter();
        out.write("There was an error: " + ex.getMessage().toString());
        out.close();
    }

}

From source file:Ctrl.Upload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  ww  w  .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 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:com.mycompany.mytubeaws.UploadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   w  ww  .  j  ava 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 {
    String result = "";
    String fileName = null;

    boolean uploaded = false;

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

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(1024 * 1024 * 40); // sets maximum size of upload file
    upload.setSizeMax(1024 * 1024 * 50); // sets maximum size of request (include file + form data)

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

        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()) {
                    fileName = item.getName();
                    UUID id = UUID.randomUUID();
                    fileName = FilenameUtils.getBaseName(fileName) + "_ID-" + id.toString() + "."
                            + FilenameUtils.getExtension(fileName);

                    File file = File.createTempFile("aws-java-sdk-upload", "");
                    item.write(file); // write form item to file (?)

                    if (file.length() == 0)
                        throw new RuntimeException("No file selected or empty file uploaded.");

                    try {
                        s3.putObject(new PutObjectRequest(bucketName, fileName, file));
                        result += "File uploaded successfully; ";
                        uploaded = true;
                    } catch (AmazonServiceException ase) {
                        System.out.println("Caught an AmazonServiceException, which means your request made it "
                                + "to Amazon S3, but was rejected with an error response for some reason.");
                        System.out.println("Error Message:    " + ase.getMessage());
                        System.out.println("HTTP Status Code: " + ase.getStatusCode());
                        System.out.println("AWS Error Code:   " + ase.getErrorCode());
                        System.out.println("Error Type:       " + ase.getErrorType());
                        System.out.println("Request ID:       " + ase.getRequestId());

                        result += "AmazonServiceException thrown; ";
                    } catch (AmazonClientException ace) {
                        System.out
                                .println("Caught an AmazonClientException, which means the client encountered "
                                        + "a serious internal problem while trying to communicate with S3, "
                                        + "such as not being able to access the network.");
                        System.out.println("Error Message: " + ace.getMessage());

                        result += "AmazonClientException thrown; ";
                    }

                    file.delete();
                }
            }
        }
    } catch (Exception ex) {
        result += "Generic exception: '" + ex.getMessage() + "'; ";
        ex.printStackTrace();
    }

    if (fileName != null && uploaded)
        result += "Generated file ID: " + fileName;

    System.out.println(result);

    request.setAttribute("resultText", result);
    request.getRequestDispatcher("/UploadResult.jsp").forward(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 ava 2 s.c o  m
    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:hu.sztaki.lpds.submitter.service.jobstatus.JobStatusServlet.java

/** 
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 * @param request servlet request//www.  j a  va2  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 {

    //System.out.println("JobStatusServlet.processRequest called !!!!!!!!!!!!!!!");
    String uid = "";
    String jobid = "";
    int status = -1;
    //sysLog(jobid, "JobStatusServlet * * * JobStatusServlet called");
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        fileItemFactory.setSizeThreshold(30 * 1024 * 1024); //1 MB
        fileItemFactory.setRepository(new File(Base.getI().getPath()));//new File()

        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);

        try {
            List items = uploadHandler.parseRequest(request);
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {
                    //                        out.println("Field Name = " + item.getFieldName() + ", Value = " + item.getString());
                    //                        System.out.println("JobStatusServlet: Field Name = " + item.getFieldName() + ", Value = " + item.getString());
                    if ("uid".equals("" + item.getFieldName())) {
                        uid = item.getString();
                    } else if ("jobid".equals("" + item.getFieldName())) {
                        jobid = item.getString();
                    } else if ("status".equals("" + item.getFieldName())) {
                        status = Integer.parseInt(item.getString());
                    }
                } else {
                    //                        System.out.println("JobStatusServlet: Field Name = " + item.getFieldName()
                    //                                + ", File Name = " + item.getName()
                    //                                + ", Content type = " + item.getContentType()
                    //                                + ", File Size = " + item.getSize());
                    //                        out.println("Field Name = " + item.getFieldName()
                    //                                + ", File Name = " + item.getName()
                    //                                + ", Content type = " + item.getContentType()
                    //                                + ", File Size = " + item.getSize());
                    // outfiles.add(item.getName());
                    if (status == 1 && GStatusHandler.getI().setStatus(uid, jobid, status)) {//if status == uploading(1) and userid->jobid
                        File destinationDir = new File(Base.getI().getPath() + jobid + "/outputs");
                        File file = new File(destinationDir, item.getName());
                        item.write(file);
                    } else {
                        System.out.println("ILLEGAL ACCESS or Deleted job!? uid:" + uid + " jobid:" + jobid);
                    }
                }

            }

        } catch (FileUploadException ex) {
            sysLog(jobid, "JobStatusServlet: Error encountered while parsing the request: " + ex
                    + " --> try getparameters");
            //ex.printStackTrace();
            uid = request.getParameter("uid");
            jobid = request.getParameter("jobid");
            try {
                if (request.getParameter("status") != null) {
                    status = Integer.parseInt(request.getParameter("status"));
                    if (status == 6) {
                        status = 66;
                    } else if (status == 7) {
                        status = 77;
                    } //running status = 55
                }
            } catch (Exception ee) {
                //ee.printStackTrace();
            }
        } catch (Exception ex) {
            sysLog(jobid, "JobStatusServlet:Error encountered while uploading file: " + ex);
            //ex.printStackTrace();
        }

        sysLog(jobid, " JobStatusServlet: status=" + status + " userid=" + uid);
        if (status != -1) {
            GStatusHandler.getI().setStatus(uid, jobid, status);
        }

        //RequestDispatcher comp = null;

        //comp = request.getRequestDispatcher("hiba.jsp");
        // comp.forward(request, response);
    } catch (Exception ee) {
        ee.printStackTrace();
    } finally {
        out.close();
    }

    //GStatusHandler.getI().getJob(jobID)

}

From source file:com.siberhus.web.ckeditor.servlet.MultipartServletRequest.java

public MultipartServletRequest(HttpServletRequest request) throws FileUploadException {
    super(request);

    //      if(!"POST".equals(request.getMethod())){
    //         return;
    //      }//from  ww w. j a  va 2  s. c o  m
    CkeditorConfig config = CkeditorConfigurationHolder.config();
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // Set factory constraints
    if (config.fileupload().sizeThreshold() != null) {
        factory.setSizeThreshold(config.fileupload().sizeThreshold());
    }
    if (config.fileupload().repository() != null) {
        factory.setRepository(config.fileupload().repository());
    }

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

    // Set overall request size constraint
    if (config.fileupload().sizeMax() != null) {
        upload.setSizeMax(config.fileupload().sizeMax());
    }
    if (config.fileupload().fileSizeMax() != null) {
        upload.setFileSizeMax(config.fileupload().fileSizeMax());
    }
    // Copy params from query string
    Enumeration<String> paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
        String paramName = paramNames.nextElement();
        String paramValues[] = request.getParameterValues(paramName);
        if (paramValues != null) {
            this.paramMap.put(paramName, Literal.list(paramValues));
        }
    }

    @SuppressWarnings("unchecked")
    List<FileItem> itemList = upload.parseRequest(request);

    for (FileItem item : itemList) {
        String fieldName = item.getFieldName();
        if (item.isFormField()) {
            List<String> values = paramMap.get(fieldName);
            if (values == null) {
                paramMap.put(fieldName, Literal.list(item.getString()));
            } else {
                values.add(item.getString());
            }
        } else {
            fileItemMap.put(fieldName, item);
            fileItems.add(item);
        }
    }
}

From source file:Control.Upload.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from w w w . ja  v  a2s .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 {
    int k = 0;
    String userid = null;
    ArrayList<String> nameImage = new ArrayList<String>();
    String album = null;
    ArrayList<String> typeImage = new ArrayList<String>();
    ArrayList<Integer> priceImage = new ArrayList<Integer>();

    String tempPath = "/temp";
    String absoluteTempPath = this.getServletContext().getRealPath(tempPath);
    if (absoluteTempPath == null) {
        String serverContext = this.getServletContext().getRealPath("/");
        String createPath = serverContext + "temp";
        File tempfolder = new File(createPath);
        tempfolder.mkdir();
        absoluteTempPath = this.getServletContext().getRealPath(tempPath);
    }
    String absoluteFilePath = this.getServletContext().getRealPath("/data/Image");
    int maxFileSize = 50 * 1024;
    int maxMemSize = 4 * 1024;

    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(maxMemSize);
        File file = new File(absoluteTempPath);

        factory.setRepository(file);
        ServletFileUpload upload = new ServletFileUpload(factory);

        //upload.setProgressListener(new MyProgressListener(out));
        List<FileItem> items = upload.parseRequest(request);

        if (items.size() > 0) {
            for (int i = items.size() - 1; i >= 0; i--) {
                if (items.get(i).isFormField()) {
                    if (null != items.get(i).getFieldName())
                        switch (items.get(i).getFieldName()) {
                        case "userid":
                            userid = items.get(i).getString();
                            break;
                        case "nameImageUpload":
                            nameImage.add(items.get(i).getString());
                            break;
                        case "albumUpload":
                            album = items.get(i).getString();
                            break;
                        case "typeImageUpload":
                            typeImage.add(items.get(i).getString());
                            break;
                        case "priceImageUpload":
                            priceImage.add(parseInt(items.get(i).getString()));
                            break;
                        default:
                            break;
                        }
                } else if ("images".equals(items.get(i).getFieldName())) {
                    if (!"".equals(items.get(i).getName()) && !items.get(i).getName().isEmpty()) {
                        String extension = null;
                        String newLink;
                        Integer newIntIdImage = Image.listImg.size() + k;
                        String newIdImage = newIntIdImage.toString();
                        if (items.get(i).getName().endsWith("jpg")) {
                            newLink = "/Image/" + newIdImage + ".jpg";
                            file = new File(absoluteFilePath + "//" + newIdImage + ".jpg");
                        } else if (items.get(i).getName().endsWith("JPG")) {
                            newLink = "/Image/" + newIdImage + ".jpg";
                            file = new File(absoluteFilePath + "//" + newIdImage + ".jpg");
                        } else if (items.get(i).getName().endsWith("png")) {
                            newLink = "/Image/" + newIdImage + ".png";
                            file = new File(absoluteFilePath + "//" + newIdImage + ".png");
                        } else if (items.get(i).getName().endsWith("PNG")) {
                            newLink = "/Image/" + newIdImage + ".png";
                            file = new File(absoluteFilePath + "//" + newIdImage + ".png");
                        } else {
                            return;
                        }
                        boolean check = Image_DAL.addImage(newLink, userid, album, nameImage.get(0),
                                typeImage.get(0), priceImage.get(0));
                        nameImage.remove(0);
                        typeImage.remove(0);
                        priceImage.remove(0);
                        if (check) {
                            items.get(i).write(file);
                            k++;
                        }
                    }
                } else {
                }
            }
            request.setAttribute("user", userid);
            RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/index");
            dispatcher.forward(request, response);
            return;
        }
        for (int i = items.size() - 1; i >= 0; i--)
            if (items.get(i).isFormField())
                if ("userid".equals(items.get(i).getFieldName()))
                    userid = items.get(i).getString();

        request.setAttribute("error", "No file upload");
        RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/index");
        dispatcher.forward(request, response);
    } catch (Exception ex) {
        System.err.println(ex);
    }
}

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

@RequestMapping(value = "EaddGastoRF.htm", method = RequestMethod.POST)
public String addGastoRF_post(@ModelAttribute("ga") gastosR ga, BindingResult result,
        HttpServletRequest request) {//from   ww  w  .j a v a2  s.  c  om
    String mensaje = "";
    String ruta = "redirect:EGastos.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:EGastos.htm";
        }
        System.out.println("Archi subido correctamente");
    } catch (Exception ex) {
        System.out.println("Error al subir archivo" + ex.getMessage());
    }

    return ruta;

}