JSF 2.2: File Upload

JSF 2.2: File Upload

Before 2.2, you have to use Richfaces, Primefaces like JSF components to provide file upload feature.

Or you must write a custom file upload component yourself.

Luckily this long waiting feature was finally added in JSF 2.2.

 
    
 
  
 
  
    
 
  
 
  


 

 

A new inputFile component is provided for file upload purpose. The usage is simple. Like other input components, put it into a h:form, and change the enctype attribute to multipart/form-data, it is a must for file upload.

@Model
public class FileUploadBean {

    @Inject Logger log;

    private Part file;

    public void upload(){
        log.info("call upload...");      
        log.log(Level.INFO, "content-type:{0}", file.getContentType());
        log.log(Level.INFO, "filename:{0}", file.getName());
        log.log(Level.INFO, "submitted filename:{0}", file.getSubmittedFileName());
        log.log(Level.INFO, "size:{0}", file.getSize());
        try {

            byte[] results=new byte[(int)file.getSize()];
            InputStream in=file.getInputStream();
            in.read(results);         
        } catch (IOException ex) {
           log.log(Level.SEVERE, " ex @{0}", ex);
        }

        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Uploaded!"));
    }

    public Part getFile() {
        return file;
    }

    public void setFile(Part file) {
        this.file = file;
    }

}

In the backend bean, use a standard Servlet 3 Part as converted type to warp the uploaded file info.

You can easily get the uploaded file info from Part API.

NOTE: The getName method will return the client id, and getSubmittedFileName returns the original file name.

Uploaded file content can be read through the getInputStream method.

你可能感兴趣的:(java,File,upload,JSF,Glassfish,JSF22,EE7)