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

發佈了76 篇原創文章 · 獲贊 6 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章