0

我正在使用 primefaces 上传图像,对其进行裁剪,然后在图形图像上显示最终图像。

该过程工作正常,但问题是当我检索要在图形图像上显示的最终图像时,流没有关闭并且文件被 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 在生命周期中被多次调用。

4

1 回答 1

0

我已经通过使用 StreamedContent 的建议 getter 解决了这个问题:

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);
    }
}
于 2016-11-29T18:42:05.380 回答