2016-11-29 31 views
0

我正在使用primefaces上傳圖像,剪裁圖像,然後在graphicImage上顯示最終圖像。Primefaces graphicImage流未關閉,文件鎖定

該過程工作正常,但問題是,當我檢索最終圖像顯示在graphicImage上時,流沒有關閉,文件被java.exe阻止,所以我遇到了問題例如在用戶註銷時刪除文件/目錄,因爲它只是一個臨時目錄。

這是我StreamedContent的消氣:

public StreamedContent getGraphicCropped() { 
    try{ 
     if (newImageName != null) { 
      File file2 = new File(pathCroppedImage); 
      InputStream input = new FileInputStream(file2); 
      graphicCropped = new DefaultStreamedContent(input); 
      showImageFinal = true; 
     } 

    } catch(Exception e){ 
     e.printStackTrace(); 
    } 

    return graphicCropped; 
} 

如果我做input.close();那麼我就能夠刪除的文件,但它沒有顯示出來,因爲我知道,這個調用getter時不止一次在生命週期。

回答

0

我用StreamedContent的建議吸氣解決它:

public StreamedContent getGraphicCropped() throws FileNotFoundException { 

    FacesContext context = FacesContext.getCurrentInstance(); 

    if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) { 
     // So, we're rendering the HTML. Return a stub StreamedContent so that it will generate right URL. 
     return new DefaultStreamedContent(); 
    } 
    else { 
     // So, browser is requesting the image. Return a real StreamedContent with the image bytes. 
     File file2 = new File(pathCroppedImage); 
     InputStream input = new FileInputStream(file2); 
     showImageFinal = true; 
     return new DefaultStreamedContent(input); 
    } 
}