Example usage for org.apache.commons.fileupload FileItem getSize

List of usage examples for org.apache.commons.fileupload FileItem getSize

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getSize.

Prototype

long getSize();

Source Link

Document

Returns the size of the file item.

Usage

From source file:com.antinymail.ventadecasas.servlet.UploadServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
    // 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  .j a v a 2  s.c om*/
    }
    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"));

    //factory.setRepository(new File("C:\\Users\\Susana\\Documents\\NetBeansProjects\\VentadeCasas\\web\\images")); 

    factory.setRepository(
            new File("C:\\Users\\Susana\\Documents\\NetBeansProjects\\VentadeCasas\\web\\images"));

    //factory.setRepository(new File("//petylde.esy.es//uploads//casapueblo"));
    //factory.setRepository(new Uri());

    // 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("\\")));

                    //file = new File( fileName);

                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));

                    //file = new File( fileName);
                }
                fi.write(file);
                //fi.write( fileNa ) ;  

                out.println("Uploaded Filename: " + fileName + "<br>");
                out.println("La ruta inicial era: " + filePath + "<br>");

            }
        }
        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:com.liferay.samplestruts.struts.action.UploadAction.java

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    FileItemFactory factory = new DiskFileItemFactory();

    ServletFileUpload upload = new ServletFileUpload(factory);

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

    Iterator<FileItem> itr = items.iterator();

    String itemName = StringPool.BLANK;

    while (itr.hasNext()) {
        FileItem item = itr.next();

        if (!item.isFormField()) {
            if (_log.isInfoEnabled()) {
                _log.info("Field name " + item.getFieldName());
            }/*w w  w.j  a  v  a  2s . c  o m*/

            itemName = item.getName();

            if (_log.isInfoEnabled()) {
                _log.info("Name " + itemName);
                _log.info("Content type " + item.getContentType());
                _log.info("In memory " + item.isInMemory());
                _log.info("Size " + item.getSize());
            }
        }
    }

    request.setAttribute("file_name", itemName);

    return mapping.findForward("/sample_struts_portlet/upload_success");
}

From source file:com.pagoadalabs.fileupload.controller.FileController.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   w  w w.  j a  va 2 s.  com*/
 * @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 {
    // 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;
    }
    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("e://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));
                }
                fi.write(file);
                out.println("Uploaded Filename: " + fileName + "<br>");
            }
        }
        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:com.pdfhow.diff.UploadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request//  ww w .j a  v  a 2s.c  om
 *            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 {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new IllegalArgumentException(
                "Request is not multipart, please 'multipart/form-data' enctype for your form.");
    }

    ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
    PrintWriter writer = response.getWriter();
    response.setContentType("application/json");
    JSONArray json = new JSONArray();
    try {
        List<FileItem> items = uploadHandler.parseRequest(request);
        for (FileItem item : items) {
            if (!item.isFormField()) {
                File file = new File(request.getServletContext().getRealPath("/") + "imgs/", item.getName());
                item.write(file);
                JSONObject jsono = new JSONObject();
                jsono.put("name", item.getName());
                jsono.put("size", item.getSize());
                jsono.put("url", "UploadServlet?getfile=" + item.getName());
                jsono.put("thumbnail_url", "UploadServlet?getthumb=" + item.getName());
                jsono.put("delete_url", "UploadServlet?delfile=" + item.getName());
                jsono.put("delete_type", "GET");
                json.put(jsono);
                System.out.println(json.toString());
            }
        }
    } catch (FileUploadException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        writer.write(json.toString());
        writer.close();
    }
}

From source file:controller.ControlPembayaran.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String timeStamp = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(Calendar.getInstance().getTime());
    String timeStamp2 = new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime());

    Pembayaran p = new Pembayaran();
    DatabaseManager db = new DatabaseManager();

    //Menyimpan file ke dalam sistem
    File file;//ww  w.j  av  a 2 s .  c  o m
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    String filePath = "c:/Apache/";

    String contentType = request.getContentType();
    if (contentType.indexOf("multipart/form-data") >= 0) {

        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(maxMemSize);
        factory.setRepository(new File("c:\\temp"));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxFileSize);
        try {
            List fileItems = upload.parseRequest(request);
            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    if (fi.getName().contains(".csv")) {
                        String fieldName = fi.getFieldName();
                        String fileName = fi.getName();
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();
                        file = new File(filePath + "DataPembayaran_" + timeStamp + ".csv");
                        fi.write(file);
                    } else {
                        throw new Exception("Format File Salah");
                    }
                }
            }
        } catch (Exception ex) {
            returnError(request, response, ex);
        }
    } else {
        Exception e = new Exception("no file uploaded");
        returnError(request, response, e);
    }
    //Membaca file dari dalam sistem
    String csvFile = filePath + "DataPembayaran_" + timeStamp + ".csv";
    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = ",";

    try {
        br = new BufferedReader(new FileReader(csvFile));
        int counter = 1;
        while ((line = br.readLine()) != null) {

            // use comma as separator
            String[] dataSet = line.split(cvsSplitBy);
            p.setID(timeStamp2 + "_" + counter);
            p.setWaktuPembayaran(dataSet[0]);
            p.setNoRekening(dataSet[1]);
            p.setJumlahPembayaran(Double.parseDouble(dataSet[2]));
            p.setNis(dataSet[3].substring(0, 5));
            p.setBulanTagihan(Integer.parseInt(dataSet[3].substring(6)));
            //Membandingkan nis, jumlah, bulan pembayaran ke tagihan
            Tagihan[] t = Tagihan.getListTagihan(p.getNis());
            for (int i = 0; i < t.length; i++) {
                if (t[i].getNis().equals(p.getNis()) && t[i].getJumlah_pembayaran() == p.getJumlahPembayaran()
                        && t[i].getBulan_tagihan() == p.getBulanTagihan())// bandingkan jumlah pembayaran
                {
                    //Masukan data pembayaran ke database
                    Pembayaran.simpanPembayaran(p);
                    //update status pembayaran tagihan
                    t[i].verifikasiSukses(p.getNis(), p.getBulanTagihan());//update status bayar tagihan menjadi sudah bayar
                }
            }
            counter++;
        }
        this.tampil(request, response, "Data Terverifikasi");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //        }
}

From source file:gov.nih.nci.queue.servlet.FileUploadServlet.java

/**
 * *************************************************
 * URL: /upload doPost(): upload the files and other parameters
 *
 * @param request/*from  w w  w. j  a v a 2 s. c om*/
 * @param response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 * **************************************************
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Create an object for JSON response.
    ResponseModel rm = new ResponseModel();
    // Set response type to json
    response.setContentType("application/json");
    PrintWriter writer = response.getWriter();

    // Get property values.
    // SOCcer related.
    final Double estimatedThreshhold = Double
            .valueOf(PropertiesUtil.getProperty("gov.nih.nci.soccer.computing.time.threshhold").trim());
    // FileUpload Settings.
    final String repositoryPath = PropertiesUtil.getProperty("gov.nih.nci.queue.repository.dir");
    final String strOutputDir = PropertiesUtil.getProperty("gov.nih.cit.soccer.output.dir").trim();
    final long fileSizeMax = 10000000000L; // 10G
    LOGGER.log(Level.INFO, "repository.dir: {0}, filesize.max: {1}, time.threshhold: {2}",
            new Object[] { repositoryPath, fileSizeMax, estimatedThreshhold });

    // Check that we have a file upload request
    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    // Ensuring that the request is actually a file upload request.
    if (isMultipart) {
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //upload file dirctory. If it does not exist, create one.
        File f = new File(repositoryPath);
        if (!f.exists()) {
            f.mkdir();
        }
        // Set factory constraints
        // factory.setSizeThreshold(yourMaxMemorySize);
        // Configure a repository
        factory.setRepository(new File(repositoryPath));

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

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

            // Process the uploaded items
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();

                if (!item.isFormField()) { // Handle file field.
                    String fileName = item.getName();
                    rm.setFileName(fileName);
                    String contentType = item.getContentType();
                    rm.setFileType(contentType);
                    long sizeInBytes = item.getSize();
                    rm.setFileSize(String.valueOf(sizeInBytes));

                    String inputFileId = new UniqueIdUtil(fileName).getInputUniqueID();
                    rm.setInputFileId(inputFileId);
                    String absoluteInputFileName = repositoryPath + File.separator + inputFileId;
                    rm.setRepositoryPath(repositoryPath);

                    // Write file to the destination folder.
                    File inputFile = new File(absoluteInputFileName);
                    item.write(inputFile);

                    // Validation.
                    InputFileValidator validator = new InputFileValidator();
                    List<String> validationErrors = validator.validateFile(inputFile);

                    if (validationErrors == null) { // Pass validation
                        // check estimatedProcessingTime.
                        SoccerServiceHelper soccerHelper = new SoccerServiceHelper(strOutputDir);
                        Double estimatedTime = soccerHelper.getEstimatedTime(absoluteInputFileName);
                        rm.setEstimatedTime(String.valueOf(estimatedTime));
                        if (estimatedTime > estimatedThreshhold) { // STATUS: QUEUE (Ask client for email)
                            // Construct Response String in JSON format.
                            rm.setStatus("queue");
                        } else { // STATUS: PASS (Ask client to confirm calculate)
                            // all good. Process the output and Go to result page directly.
                            rm.setStatus("pass");
                        }
                    } else { // STATUS: FAIL // Did not pass validation.
                        // Construct Response String in JSON format.
                        rm.setStatus("invalid");
                        rm.setDetails(validationErrors);
                    }
                } else {
                    // TODO: Handle Form Fields such as SOC_SYSTEM.
                } // End of isFormField
            }
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "FileUploadException or FileNotFoundException. Error Message: {0}",
                    new Object[] { e.getMessage() });
            rm.setStatus("fail");
            rm.setErrorMessage(
                    "Oops! We met with problems when uploading your file. Error Message: " + e.getMessage());
        }

        // Send the response.
        ObjectMapper jsonMapper = new ObjectMapper();
        LOGGER.log(Level.INFO, "Response: {0}", new Object[] { jsonMapper.writeValueAsString(rm) });
        // Generate metadata file
        new MetadataFileUtil(rm.getInputFileId(), repositoryPath)
                .generateMetadataFile(jsonMapper.writeValueAsString(rm));
        // Responde to the client.
        writer.print(jsonMapper.writeValueAsString(rm));

    } else { // The request is NOT actually a file upload request
        writer.print("You hit the wrong file upload page. The request is NOT actually a file upload request.");
    }
}

From source file:com.finedo.base.utils.upload.FileUploadUtils.java

public static final List<FileInfo> saveFiles(String uploadDir, List<FileItem> list) {

    List filelist = new ArrayList();

    if (list == null) {
        return filelist;
    }//  ww  w .j a  v  a2  s  . c o  m

    File dir = new File(uploadDir);
    if (!(dir.isDirectory())) {
        dir.mkdirs();
    }

    String uploadPath = uploadDir;

    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("utf-8");
    Iterator it = list.iterator();
    String name = "";
    String extName = "";

    while (it.hasNext()) {
        FileItem item = (FileItem) it.next();
        if (!(item.isFormField())) {
            name = item.getName();
            logger.info("saveFiles name=============" + name);

            if (name == null)
                continue;
            if (name.trim().equals("")) {
                continue;
            }

            if (name.lastIndexOf(".") >= 0) {
                extName = name.substring(name.lastIndexOf("."));
            }

            File file = null;
            do {
                name = UUID.randomUUID().toString();
                file = new File(uploadPath + name + extName);
            } while (file.exists());

            File saveFile = new File(uploadPath + name + extName);
            try {
                item.write(saveFile);
            } catch (Exception e) {
                e.printStackTrace();
            }

            String fileName = item.getName().replace("\\", "/");

            String[] ss = fileName.split("/");
            fileName = trimExtension(ss[(ss.length - 1)]);

            FileInfo fileinfo = new FileInfo();
            fileinfo.setName(fileName);
            fileinfo.setUname(name);
            fileinfo.setFilePath(uploadDir);
            fileinfo.setFileExt(extName);
            fileinfo.setSize(String.valueOf(item.getSize()));
            fileinfo.setContentType(item.getContentType());
            fileinfo.setFieldname(item.getFieldName());
            filelist.add(fileinfo);
        }
    }
    return filelist;
}

From source file:de.suse.swamp.modules.actions.WorkflowActions.java

/**
 * Store the uploaded workflow to a temp. directory and verify it
 *///from ww  w  .ja  va 2s . c  o  m
public void doUploadworkflow(RunData data, Context context) throws Exception {

    org.apache.turbine.util.parser.ParameterParser pp = data.getParameters();
    String separator = System.getProperty("file.separator");
    String tmpdir = System.getProperty("java.io.tmpdir");
    ArrayList results = new ArrayList();
    // storing file
    FileItem fi = pp.getFileItem("filename");
    if (fi == null || fi.getName() == null || fi.getSize() == 0) {
        throw new Exception("Empty file uploaded.");
    }

    if (fi.getName().endsWith(".xml") || fi.getName().endsWith(".zip")) {
        String uniqueid = String.valueOf(new Date().getTime());
        String basePath = tmpdir + separator + uniqueid;
        FileUtils.forceMkdir(new File(basePath));
        WorkflowReadResult result = null;

        if (fi.getName().endsWith("xml")) {
            File wfTmpFile = new File(basePath + separator + "workflow.xml");
            if (wfTmpFile.exists()) {
                wfTmpFile.delete();
            }
            fi.write(wfTmpFile);
            if (!wfTmpFile.exists()) {
                throw new Exception("Storing of file: " + fi.getName() + " failed.");
            }
        } else {
            // unpack uploaded workflow resource bundle
            de.suse.swamp.util.FileUtils.uncompress(fi.getInputStream(), basePath);
        }
        // read + verify the workflow:
        WorkflowReader reader = new WorkflowReader(new File(basePath));
        result = reader.readWorkflow(basePath);
        results.add(result);
        context.put("uniqueid", uniqueid);
        // clean uploaded stuff on errors
        if (result.hasErrors()) {
            FileUtils.deleteDirectory(new File(basePath));
        }
    } else {
        throw new Exception(
                "Only upload of single \"workflow.xml\" and \".zip\" packed workflow bundles is supported.");
    }
    context.put("workflowreadresults", results);
}

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;/* w ww  .j  a v  a  2 s.c  om*/
    }
    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:controlador.SerCandidato.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    //ruta relativa en donde se guardan las fotos de candidatos
    String ruta = getServletContext().getRealPath("/") + "images/files/candidatos/";
    //Partido p = new Partido();
    Candidato c = new Candidato();
    int accion = 1; //1=gregar  2=modificar
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        diskFileItemFactory.setSizeThreshold(40960);
        File repositoryPath = new File("/temp");
        diskFileItemFactory.setRepository(repositoryPath);
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        servletFileUpload.setSizeMax(81920); // bytes
        upload.setSizeMax(307200); // 1024 x 300 = 307200 bytes = 300 Kb
        List listUploadFiles = null;
        FileItem item = null;
        try {//  w  ww. j  av  a2s .  c om
            listUploadFiles = upload.parseRequest(request);
            Iterator it = listUploadFiles.iterator();
            while (it.hasNext()) {
                item = (FileItem) it.next();
                if (!item.isFormField()) {
                    if (item.getSize() > 0) {
                        String nombre = item.getName();
                        String tipo = item.getContentType();
                        long tamanio = item.getSize();
                        String extension = nombre.substring(nombre.lastIndexOf("."));
                        File archivo = new File(ruta, nombre);
                        item.write(archivo);
                        if (archivo.exists()) {
                            c.setFoto(nombre);
                        } else {
                            out.println("FALLO AL GUARDAR. NO EXISTE " + archivo.getAbsolutePath() + "</p>");
                        }
                    }
                } else {
                    //se reciben los campos de texto enviados y se igualan a los atributos del objeto
                    if (item.getFieldName().equals("slPartido")) {
                        c.setIdPartido(Integer.parseInt(item.getString()));
                    }
                    if (item.getFieldName().equals("slDepartamento")) {
                        c.setIdDepartamento(Integer.parseInt(item.getString()));
                    }
                    if (item.getFieldName().equals("txtDui")) {
                        c.setNumDui(item.getString());
                    }
                    if (item.getFieldName().equals("txtId")) {
                        c.setIdCandidato(Integer.parseInt(item.getString()));
                    }
                    if (item.getFieldName().equals("txtTipo")) {
                        //definimos que el candidato es tipo 1 (Partidario)
                        c.setTipo(Integer.parseInt(item.getString()));
                    }

                }
            }
            //si no se selecciono una imagen distinta, se conserva la imagen anterior
            if (c.getFoto() == null) {
                c.setFoto(CandidatoDTO.mostrarCandidato(c.getIdCandidato()).getFoto());
            }

            //cuando se presiona el boton de agregar
            if (c.getIdCandidato() == 0) {
                if (CandidatoDTO.agregarCandidato(c)) {
                    //candidato partidario = 1
                    //candidato independiente = 2
                    if (c.getTipo() == 1) {
                        //crud de canidatos partidadios
                        response.sendRedirect(this.redireccionJSP);
                    } else {
                        //crud de canidatos independientes
                        response.sendRedirect(this.redireccionJSP2);
                    }
                } else {
                    //cambiar por alguna accion en caso de error
                    out.print("Error al insertar");
                }
            } //cuando se presiona el boton de modificar
            else {
                if (CandidatoDTO.modificarCandidato(c)) {
                    if (c.getTipo() == 1) {
                        //crud de canidatos partidadios
                        response.sendRedirect(this.redireccionJSP);
                    } else {
                        //crud de canidatos independientes
                        response.sendRedirect(this.redireccionJSP2);
                    }
                } else {
                    out.print("Error al modificar");
                }
            }

        } catch (FileUploadException e) {
            out.println("Error Upload: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            out.println("Error otros: " + e.getMessage());
            e.printStackTrace();
        }
    }
}