Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.telecel.controllers; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Map; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.context.FacesContext; import org.apache.commons.io.FilenameUtils; import org.primefaces.event.FileUploadEvent; /** * * @author primrose */ @ManagedBean @RequestScoped public class UploadBean { public final static String destination = "/usr/files/"; public static String fileName; public final static String tempFileName = "TEMP"; public static String extension = ""; File f = null; /** * Creates a new instance of UploadBean */ public UploadBean() { } public void upload(FileUploadEvent event) { System.out.println("file uploading"); Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext() .getRequestParameterMap(); fileName = params.get("documentName"); FacesMessage msg = new FacesMessage("Success! ", event.getFile().getFileName() + " is uploaded."); FacesContext.getCurrentInstance().addMessage(null, msg); try { copyFile(event.getFile().getFileName(), event.getFile().getInputstream()); f = (File) event.getFile(); } catch (IOException e) { e.printStackTrace(); } } public String getExtension(File file) { String ext; ext = FilenameUtils.getExtension(file.getAbsolutePath()); return ext; } public void copyFile(String fileName, InputStream in) { try { // write the inputStream to a FileOutputStream System.out.println("file copying"); OutputStream out = new FileOutputStream(new File(destination + tempFileName + getExtension(f))); extension = getExtension(f); int read = 0; byte[] bytes = new byte[1024]; while ((read = in.read(bytes)) != -1) { out.write(bytes, 0, read); } System.out.println("New file created!"); // printTOSOW(fileName); } catch (IOException e) { System.out.println(e.getMessage()); } } public String getFileName() { return fileName; } public void setFileName(String fileName) { UploadBean.fileName = fileName; } }