0

I'm using primefaces to upload an image, crop it and then display the final image on a graphicImage.

The process works fine, but the problem is that when I retrieve the final image to display on the graphicImage, the stream is not closed and the file is being held up by java.exe, so I'm having problems on deleting the files/directory for example when the user logs out, because it's just a temp directory.

This is the getter of my 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;
}

If I do input.close();then I'm able to delete the file, but it is not displayed, because I know that this getter is called more than once on the life cycle.

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452

1 Answers1

0

I've solved it by using the suggested getter of a 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);
    }
}