primefaces 檔案上傳下載的配置
結合了幾篇外國友人的帖子和primefaces文件:
一、上傳
1、在web.xml中新增
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>auto|native</param-value>
</context-param>
本人親測commons不可用,就算加入filter
2.1 簡單方式上傳
<h:form enctype="multipart/form-data">
<p:fileUpload value="#{fileBean.file}" mode="simple" />
<p:commandButton value="Submit" ajax="false"/>
</h:form>
這個是針對mode=simple的上傳方案,如果mode=advanced,去掉enctype="multipart/form-data"不然介面會出現錯誤
這裡,commandButton的ajax必須是false
2.2 高階方式上傳
<p:panelGrid columns="2">
<h:outputLabel for="image" value="Select Image: *" />
<p:fileUpload fileUploadListener="#{productBean.handleFileUploadx}" mode="advanced" label="選擇檔案" uploadLabel="點此上傳" cancelLabel="取消" allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/>
<f:facet name="footer">
<p:commandButton value="Submit" >
<f:ajax render="testimg"/>
</p:commandButton>
</f:facet>
</p:panelGrid>
3、得到byte[]
前臺
<p:graphicImage id="testimg" value="#{productBean.image}" width="50" height="50" style="">
</p:graphicImage>
後臺
private StreamedContent image;
get
set
public void handleFileUploadx(FileUploadEvent event) {
UploadedFile f=event.getFile();
setFile( event.getFile());
try {
InputStream stream;
stream = file.getInputstream();
byte[] bt=IOUtils.toByteArray(stream);
ByteArrayInputStream img=new ByteArrayInputStream(bt);
setImage( new DefaultStreamedContent(img,"image/jpg"));
} catch (IOException ex) {
Logger.getLogger(ProductBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
這裡 IOUtils是Apache的common-io在本人的資源中提供下載,當然,得到位元組流之後你可以把它存入資料庫,需要的時候在取出來,我這裡只是展示了上傳完檔案之後顯示上傳檔案的功能。
如果你想把上傳的file儲存成檔案
InputStream stream=file.getInputstream();
FileOutputStream fos=new FileOutputStream(new File("/dd.jpg"));
int read=0;
byte[] bytes=new byte[1024];
while((read=stream.read(bytes))!=-1)
{
fos.write(bytes,0,read);
}
二、下載
前臺
<p:commandLink value="Download" ajax="false">
<p:fileDownload value="#{fileBean.downfile}"/>
</p:commandLink>
後臺
初始化的時候
InputStream stream = this.getClass().getResourceAsStream("./ok.png");
setDownfile(new DefaultStreamedContent(stream, "image/jpeg","dx.jpg"));
這樣,就可以把上傳資源以二進位制的方式存入資料庫,需要下載的時候,在從資料庫中取出以提供下載。
三、實體類的二進位制表示
@Lob
private byte[] file;
set
get