2016-11-29 75 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); 
    } 
}