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

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

Introduction

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

Prototype

void write(File file) throws Exception;

Source Link

Document

A convenience method to write an uploaded item to disk.

Usage

From source file:Controlador.imagenes.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w  ww  . ja  va2  s.  co  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, FileUploadException {

    String archivourl = "D:\\Carlos Ivn\\Desktop\\CMSProductos\\web\\recursos\\imagenes\\index";

    DiskFileItemFactory factory = new DiskFileItemFactory();

    factory.setSizeThreshold(1024);

    factory.setRepository(new File(archivourl));

    ServletFileUpload upload = new ServletFileUpload(factory);
    String cod = "";

    PrintWriter out = response.getWriter();

    try {

        String nom = "";
        List<FileItem> partes = upload.parseRequest(request);
        Iterator<FileItem> it = partes.iterator();
        FileItem fileItem = it.next();
        if ("txtImagen1".equals(fileItem.getFieldName())) {
            nom = "\\c1.jpg";
        } else if ("txtImagen2".equals(fileItem.getFieldName())) {
            nom = "\\ca2.jpg";
        } else if ("txtImagen3".equals(fileItem.getFieldName())) {
            nom = "\\ca3.jpg";
        } else if ("txtImagenn".equals(fileItem.getFieldName())) {
            archivourl = "D:\\Carlos Ivn\\Desktop\\CMSProductos\\web\\recursos\\imagenes\\nosotros";
            nom = "\\portada.jpg";
        }
        out.print(fileItem.getFieldName());
        for (FileItem items : partes) {
            File file = new File(archivourl, items.getName());
            String ruta = archivourl + "\\" + items.getName();
            String ruta2 = archivourl + nom;
            out.println(ruta);
            // verificar si existe el nombre y borrarlo
            if (ruta == null ? ruta2 != null : !ruta.equals(ruta2)) {
                File file2 = new File(ruta2);
                file2.delete();
            }
            //  cambiar el nombre del archivo    
            items.write(file);
            File archivo = new File(ruta);
            archivo.renameTo(new File(ruta2));

        }
        if (nom == "\\portada.jpg") {
            response.sendRedirect("Administrador/Paginas/nosotros.jsp");
        } else
            response.sendRedirect("Administrador/Paginas/inicio.jsp");
    } catch (Exception e) {
        out.print("ERROR " + e.getMessage() + "");
        //response.sendRedirect("Administrador/Paginas/inicio.jsp");
    }
}

From source file:hudson.PluginManager.java

/**
 * Uploads a plugin./*from  w ww  .  ja  v a2s. c o m*/
 */
public HttpResponse doUploadPlugin(StaplerRequest req) throws IOException, ServletException {
    try {
        Hudson.getInstance().checkPermission(Hudson.ADMINISTER);

        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

        // Parse the request
        FileItem fileItem = (FileItem) upload.parseRequest(req).get(0);
        String fileName = Util.getFileName(fileItem.getName());
        if (!fileName.endsWith(".hpi"))
            throw new Failure(hudson.model.Messages.Hudson_NotAPlugin(fileName));
        fileItem.write(new File(rootDir, fileName));
        fileItem.delete();

        pluginUploaded = true;

        return new HttpRedirect(".");
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {// grrr. fileItem.write throws this
        throw new ServletException(e);
    }
}

From source file:com.es.keyassistant.resolvers.Resolver0004.java

@Override
public ServiceResult execute() throws Exception {
    File dir = new File(getRequest().getServletContext().getRealPath(TMP_PATH));
    dir.mkdirs();/* w w w. j  a  v a2  s .com*/

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(5 * 1024);
    factory.setRepository(dir);
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    upload.setSizeMax(5 * 1024 * 1024);
    List<FileItem> formItems = upload.parseRequest(getRequest());

    DetectionInfo info = new DetectionInfo();
    assignPropertiesTo(formItems, info);

    for (FileItem formItem : formItems) {
        if (!formItem.isFormField()) {
            String fileName = formItem.getName();
            String targetFileName = generateDectionFileName(fileName, info);
            info.setDetectionFileName(targetFileName);
            info.setDetectionFilePath(String.format("%s/%s", STORE_PATH, targetFileName));

            File storeDir = new File(getRequest().getServletContext().getRealPath(STORE_PATH));
            storeDir.mkdirs();
            File detectionFile = new File(storeDir, targetFileName);

            formItem.write(detectionFile);

            formItem.delete();
            break;
        }
    }

    if (info.getDetectionSN() == null) {
        throw new ClientException(ClientException.REQUEST_ERROR, "");
    }

    ContentService service = new ContentService();
    if (service.addDetectionInfo(info) < 0) {
        throw new ClientException(ClientException.REQUEST_ERROR, "??");
    }

    ServiceResult result = new ServiceResult();
    result.getData().add(makeMapByKeyAndValues("receiptNumber", info.getDetectionSN()));

    return result;
}

From source file:com.mycompany.mytubeaws.UploadServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  w ww.  j  a  v a2 s.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:edu.brown.cs32.siliclone.servlets.SampleUploadServlet.java

/**
 * Override executeAction to save the received files in a custom place
 * and delete this items from session.  
 */// w w w .j  a v a2 s  . co  m
@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    System.out.println("RUNNING EXECUTE ACTION");
    for (FileItem item : sessionFiles) {
        System.out.println("looping");
        if (false == item.isFormField()) {
            try {
                /// Create a new file based on the remote file name in the client
                // String saveName = item.getName().replaceAll("[\\\\/><\\|\\s\"'{}()\\[\\]]+", "_");
                // File file =new File("/tmp/" + saveName);
                /// Create a temporary file
                // File file = File.createTempFile("upload-", ".bin", new File("/tmp"));
                File file = File.createTempFile("upload-", ".bin");
                item.write(file);
                receivedFiles.put(item.getFieldName(), file);
                receivedContentTypes.put(item.getFieldName(), item.getContentType());
            } catch (Exception e) {
                throw new UploadActionException(e.getMessage());
            }
        }
        removeSessionFileItems(request);
    }
    return null;
}

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  ww  w.  j  a v  a2s  .c  om*/
    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:com.openhr.company.UploadCompLicenseFile.java

@Override
public ActionForward execute(ActionMapping map, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // checks if the request actually contains upload file
    if (!ServletFileUpload.isMultipartContent(request)) {
        PrintWriter writer = response.getWriter();
        writer.println("Request does not contain upload data");
        writer.flush();//from  w w w  . jav a 2 s.c  o m
        return map.findForward("HRHome");
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    String uploadPath = 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
        List formItems = upload.parseRequest(request);
        Iterator iter = formItems.iterator();

        // iterates over form's fields
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // 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);

                // Read the file object contents and parse it and store it in the repos
                FileInputStream fstream = new FileInputStream(storeFile);
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String strLine;

                //Read File Line By Line
                while ((strLine = br.readLine()) != null) {
                    System.out.print("Processing line - " + strLine);

                    String[] lineColumns = strLine.split(COMMA);

                    if (lineColumns.length < 8) {
                        br.close();
                        in.close();
                        fstream.close();
                        throw new Exception("The required columns are missing in the line - " + strLine);
                    }

                    // Format is - CompID,CompName,Branch,Address,From,To,LicenseKey,FinStartMonth
                    String companyId = lineColumns[0];
                    String companyName = lineColumns[1];
                    String branchName = lineColumns[2];
                    String address = lineColumns[3];
                    String fromDateStr = lineColumns[4];
                    String toDateStr = lineColumns[5];
                    String licenseKey = lineColumns[6];
                    String finStartMonthStr = lineColumns[7];

                    Date fromDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ENGLISH)
                            .parse(fromDateStr);
                    Date toDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ENGLISH).parse(toDateStr);
                    address = address.replace(";", ",");

                    List<Company> eComp = CompanyFactory.findByName(companyName);
                    if (eComp == null || eComp.isEmpty()) {
                        Company company = new Company();
                        company.setCompanyId(companyId);
                        company.setName(companyName);
                        company.setFystart(Integer.parseInt(finStartMonthStr));

                        Branch branch = new Branch();
                        branch.setAddress(address);
                        branch.setCompanyId(company);
                        branch.setName(branchName);

                        Licenses license = new Licenses();
                        license.setActive(1);
                        license.setCompanyId(company);
                        license.setFromdate(fromDate);
                        license.setTodate(toDate);
                        license.formLicenseKey();

                        System.out.println("License key formed - " + license.getLicensekey());
                        System.out.println("License key given - " + licenseKey);
                        if (license.getLicensekey().equalsIgnoreCase(licenseKey)) {
                            CompanyFactory.insert(company);
                            BranchFactory.insert(branch);
                            LicenseFactory.insert(license);
                        } else {
                            br.close();
                            in.close();
                            fstream.close();

                            throw new Exception("License is tampared. Contact Support.");
                        }
                    } else {
                        // Company is present, so update it.
                        Company company = eComp.get(0);
                        List<Licenses> licenses = LicenseFactory.findByCompanyId(company.getId());

                        Licenses newLicense = new Licenses();
                        newLicense.setActive(1);
                        newLicense.setCompanyId(company);
                        newLicense.setFromdate(fromDate);
                        newLicense.setTodate(toDate);
                        newLicense.formLicenseKey();

                        System.out.println("License key formed - " + newLicense.getLicensekey());
                        System.out.println("License key given - " + licenseKey);

                        if (newLicense.getLicensekey().equalsIgnoreCase(licenseKey)) {
                            for (Licenses lic : licenses) {
                                if (lic.getActive().compareTo(1) == 0) {
                                    lic.setActive(0);
                                    LicenseFactory.update(lic);
                                }
                            }

                            LicenseFactory.insert(newLicense);
                        } else {
                            br.close();
                            in.close();
                            fstream.close();

                            throw new Exception("License is tampared. Contact Support.");
                        }
                    }
                }

                //Close the input stream
                br.close();
                in.close();
                fstream.close();
            }
        }
        System.out.println("Upload has been done successfully!");
    } catch (Exception ex) {
        System.out.println("There was an error: " + ex.getMessage());
        ex.printStackTrace();
    }

    return map.findForward("CompLicHome");
}

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;/*from  w w  w  .  j av  a  2 s .  co  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:Controlador.UploadController.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    //verificar el multipart/form-data
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    String name = request.getParameter("name");
    try (PrintWriter out = response.getWriter()) {
        out.println("Nombre: " + name);
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            try {
                List items = upload.parseRequest(request);
                Iterator iterator = items.iterator();
                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();

                    if (!item.isFormField()) {
                        String fileName = item.getName();

                        String root = getServletContext().getRealPath("/imagenes/");
                        File path = new File(root);
                        if (!path.exists()) {
                            boolean status = path.mkdirs();
                        }//from   w w w .j av  a2  s  .c om

                        File uploadedFile = new File(path + "/" + fileName);
                        out.println(uploadedFile.getAbsolutePath());
                        item.write(uploadedFile);
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:br.com.ecommkw.rest.UploadFile.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)/* ww  w. j  ava2s .c  om*/
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

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

        try {
            // Parse the request
            @SuppressWarnings("rawtypes")
            List /* FileItem */ items = upload.parseRequest(request);
            @SuppressWarnings("rawtypes")
            Iterator iterator = items.iterator();
            while (iterator.hasNext()) {
                FileItem item = (FileItem) iterator.next();
                if (!item.isFormField()) {
                    String fileName = item.getName();
                    String root = getServletContext().getRealPath("/");
                    File path = new File(root + "/pics");
                    if (!path.exists()) {
                        @SuppressWarnings("unused")
                        boolean status = path.mkdirs();
                    }

                    File uploadedFile = new File(path + "/" + fileName);
                    System.out.println(uploadedFile.getAbsolutePath());
                    item.write(uploadedFile);
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}