Search code examples
fileapache-poirestful-architecturerestful-urlhttp-error

HTTP 204 error when sending File in response REST


This is my write to excel method which returns javax.ws.rs.core.Response

public  Response writeToExcel(UserDeatilsVOWrapper listBook) {
    XSSFWorkbook  workbook = new XSSFWorkbook();
    XSSFSheet spreadsheet = workbook.createSheet("Resource Information");

    int rowCount = 0;
    createHeaderRow(spreadsheet);
    for (UserDetailsVO detailsVO : listBook.getUserDetailsList()) {
        Row row = spreadsheet.createRow(++rowCount);
        writeBook(detailsVO, row);
    }
    Response response = null;

    try (FileOutputStream outputStream = new FileOutputStream(new File("ResourceInformation.xlsx"))) {
        workbook.write(outputStream);

        // header required to enable download pop-up and set file name
        Response.ok().header("Content-Disposition", "attachment; filename=" + "ResourceInformation.xlsx").build();
    }   

    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return response;
}

This is my web service:

@POST
    @Path(WebServiceConstants.DOWNLOAD_EXCEL)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response getFile(UserDeatilsVOWrapper wrapper) {
   Response respose=new ExportToExcel().writeToExcel(wrapper);
    return respose;}

I get a HTTP204 error. I'm using postman. I know, I'm doing a big mistake in write to excel method and when trying to send file along with response. Also is there any possible way to write a file object on REST response without saving file on server? I'm doing terrible in here. any help is appreciated.


Solution

  • I do not see where you set your file to the response. Normally you would do something like this

    File file = new File("ResourceInformation.xlsx"))
    
    // Do your excel-writing here...
    
    ResponseBuilder response = Response.ok((Object) file);
    response.header("Content-Disposition", "attachment; filename=" + "ResourceInformation.xlsx");
    return response.build();