Search code examples
javaweb-servicesdownloadresteasyxssf

Unable to download xlsx from web service


I am trying to download xlsx file generated using Apache XSSF from RESTEasy based web service.

I can download the file but when double clicked to open, it says file can not be openend:

enter image description here

Below is the source code:

Web service controller:

@GET
@Path(/download)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadFile() {

    ByteArrayOutputStream baos = myService.processGbiValidationExceptions();

    ResponseBuilder response = Response.ok((Object) baos.toByteArray());
    response.header("Content-Disposition", "attachment;filename=My_File.xlsx");
    return response.build();
}

Service:

public ByteArrayOutputStream processGbiValidationExceptions() {
    XSSFWorkbook workbook = new XSSFWorkbook();

    // code to write to workbook


    // Create stream
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        workbook.write(baos);
    } catch (IOException e) {
        LOGGER.error("Error occurred while writing workbook to stream", e);
        throw new IptException(e);
    }

    return baos;
}

Any clues what I am doing incorrect over here? Thanks

P.S.: I am on Mac!


Solution

  • There were few problems with my client side code which I used previously to download the file. Now, I am using download.js and it works.

    Below is the code:

     import download from 'downloadjs';    
        .
        .
        .
        fetch(FETCH_URL, {
          method: 'GET',
          dataType: 'json',
          credentials: 'include'
        }).then(response => {
            if(response.status === 200) {
                return response.blob();
            }
          }, () => {
            // when error do something
          }
        ).then(
          // Following line helps download
          blob => download(blob, "someexcel.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        )
    

    Also, the MIME type needs to be set to application/vnd.openxmlformats-officedocument.spreadsheetml.sheet in order to download xlsx file:

    @Produces("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    

    Cheers