2013-04-12 12 views
6

我使用Primefaces如何使用流式內容與號碼:fileDownload下載非類路徑文件

號碼:fileDownload

下載一個文件,該文件是不是在類路徑中。
所以我通過FileInputStream作爲參數DefaultStreamedContent
每一件事情時,工作我豆保持在@SessionScoped ...精細,

java.io.NotSerializableException:java.io.FileInputStream中

被拋出時,我保持我的豆在@Viewscoped

我的代碼:

DownloadBean.java

@ManagedBean 
@ViewScoped 
public class DownloadBean implements Serializable { 

    private StreamedContent dFile; 

    public StreamedContent getdFile() { 
     return dFile; 
    } 

    public void setdFile(StreamedContent dFile) { 
     this.dFile = dFile; 
    } 

    /** 
    * This Method will be called when download link is clicked 
    */ 
    public void downloadAction() 
    { 
     File tempFile = new File("C:/temp.txt"); 
     try { 
      dFile = new DefaultStreamedContent(new FileInputStream(tempFile), new MimetypesFileTypeMap().getContentType(tempFile)); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 
    } 

} 

的index.xhtml

<h:form> 
    <h:commandLink action="#{downloadBean.downloadAction}"> 
     Download 
     <p:fileDownload value="#{downloadBean.dFile}"/> 
    </h:commandLink> 
</h:form> 

難道沒有使它工作的任何方法?

回答

11

引發NotSerializableException是因爲視圖範圍由JSF視圖狀態表示,在狀態爲服務器端狀態保存的情況下,該視圖狀態又可以序列化爲HTTP會話,或者在客戶端狀態保存的情況下爲HTML隱藏輸入域。 FileInputStream不能以序列化的形式表示。

如果您絕對需要保留bean視圖範圍,那麼您不應該聲明StreamedContent作爲實例變量,而是在getter方法中重新創建它。誠然,在getter方法中做業務邏輯通常是不被接受的,但StreamedContent是一個相當特殊的情況。在操作方法中,您應該只准備稍後在DefaultStreamedContent構建期間使用的可序列化變量。

@ManagedBean 
@ViewScoped 
public class DownloadBean implements Serializable { 

    private String path; 
    private String contentType; 

    public void downloadAction() { 
     path = "C:/temp.txt"; 
     contentType = FacesContext.getCurrentInstance().getExternalContext().getMimeType(path); 
    } 

    public StreamedContent getdFile() throws IOException { 
     return new DefaultStreamedContent(new FileInputStream(path), contentType); 
    } 

} 

(請注意,我也是固定的方式來獲取內容類型,你有這樣更自由地通過<mime-mapping>條目web.xml配置MIME類型)

<p:graphicImage>具有的方式與StreamedContent完全相同的問題。另請參閱Display dynamic image from database with p:graphicImage and StreamedContent

+0

非常感謝BelusC。它像一個魅力。我忘了關於實例變量和序列化的規則。 –

相關問題