Java Reference
In-Depth Information
<h:commandButton action="#{ajaxBean.uploadFile}" value="Upload File"/>
The value attribute of the inputFile component is set to a variable of type javax.servlet.http.Part within
the AjaxBean managed bean, and the commandButton has an action set to the managed bean's uploadFile method.
In this particular example, a validator is applied to the file, which can contain code that is necessary to ensure
the file for upload meets the standards for your application. The following example validator class,
org.javaee7.chapter02.FileValidator , demonstrates how to write such a validator:
@FacesValidator(value = "FileValidator")
public class FileValidator implements Validator {
public FileValidator() {
public void validate(FacesContext context, UIComponent component, Object value)
throws ValidatorException {
Part file = (Part) value;
String text = null;
try {
InputStream is = file.getInputStream();
text = new Scanner(is).useDelimiter("\\A").next();
} catch (Exception ex) {
throw new ValidatorException(new FacesMessage("Exception thrown"));
In the uploadFile method, the file is being stored into a directory named /Java_Dev/ on the server. The sources
for the uploadFile method are as follows:
public void uploadFile() {
try(InputStream is = file.getInputStream()) {
int i = is.available();
byte[] b = new byte[i];;
String fileName = getFileName(upFile);
FileOutputStream os = new FileOutputStream("/Java_Dev/" + fileName);
} catch (IOException ex) {
Logger.getLogger(AjaxBean.class.getName()).log(Level.SEVERE, null, ex);
private String getFileName(Part part) {
String partHeader = part.getHeader("content-disposition");
Search WWH ::

Custom Search