3

I have got this error message when I'm trying to download file :

Could not handle exception!: java.lang.IllegalStateException: UT010006: Cannot call getWriter(), getOutputStream() already called.

File is downloaded but without extension. So browser ask me what program should be use to read it.

This is my downloading code:

    InputStream fileIs = null;
    OutputStream output = null;
    try {            
        ExternalContext externalContext = getContext().getExternalContext();
        externalContext.responseReset();
        externalContext.setResponseContentType(fileToDownload.getMetadata().getMimeType());
        externalContext.setResponseContentLength(fileToDownload.getMetadata().getTaille().intValue());
        externalContext.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileToDownload.getMetadata().getFileName() + "\"");

        output = externalContext.getResponseOutputStream();
        Response repGetFile = ClientBuilder.newClient()
                 .target(fileToDownload.getMetadata().getFileURL())
                 .request().header("Authorization", "Bearer bearercode")
                 .get();

        fileIs = repGetFile.readEntity(InputStream.class);
        int readBytes;
        byte[] buffer = new byte[1024];
        while((readBytes = fileIs.read(buffer)) > 0){
            output.write(buffer, 0, readBytes);
        }
        output.flush();

    } catch (IOException ex) {
        LOG.log(Level.SEVERE, null, ex);
    } finally{
        try {
            fileIs.close();
            output.close();
        } catch (IOException ex) {
            LOG.log(Level.INFO, null, ex);
        }
    } 
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
ambefr
  • 71
  • 1
  • 1
  • 5

2 Answers2

1

You forgot call to:

getContext().responseComplete();

After set the headers.

Ernesto Campohermoso
  • 7,213
  • 1
  • 40
  • 51
0

i believe the problem is that you only output.flush() the file in the try body. The file is closed only when an exception is created later inside the finally body that you also include in another try body. I believe you should close the output after the 1st flush.

 output.flush();
 output.close();
ckinfos
  • 121
  • 1
  • 8