mercredi 17 septembre 2008

Upload a file with JBoss Seam

Uploading a file with JBoss Seam is a really simple thing thaks to the component

<s:uploadFile />

Here is a use in a view :


<f:facet name="header">Upload a file</f:facet>
<br/>

<h:form id="fooForm" enctype="multipart/form-data">

<s:fileUpload id="file"
data="#{uploadHandler.file}"
accept="image/jpg"/>

<h:inputText
converter="#{bankAccountConverter}"
value="#{myBean.bankAccount}" />

<h:commandButton
id="upload"
value="Upload !!"
action="#{uploadHandler.handleUpload}"/>

</h:form>


Now here is the use on the component side :


@Name("uploadHandler")
@Scope(ScopeType.EVENT)
public class UploadHandler {

@In(value="#{facesContext}")
FacesContext facesContext;

@Logger private Log log;


private byte[] file;

public void handleUpload() throws IOException{

String path = ((ServletContext) facesContext.getExternalContext().getContext()).getRealPath("/my/files/dir");
File f = new File(path,"myFile.txt");
log.info(f);
FileOutputStream fo = new FileOutputStream(f);
fo.write(file);
fo.flush();
fo.close();

}

public byte[] getFile() {
return file;
}

public void setFile(byte[] file) {
this.file = file;
}

}


Et voila !!

Aucun commentaire: