JAX-RS | Download PDF from Base64 encoded data

2019-08-07 01:22发布

问题:

Folks,

I have a REST controller that calls a service to get a BASE 64 encoded string that represents a PDF. I'm calling my REST endpoint through an AJAX call. I basically want the user to actually download a PDF file when they click on a link.

Here is the REST controller:

@GET
    @Path("/getinvoice/{invoiceid}.pdf")
    @Produces("application/pdf")
    @Consumes(MediaType.TEXT_HTML)
    public Response invoice(@PathParam("invoiceid") final String invoiceid) throws ShoppingCartException, UnexpectedErrorFault_Exception,
            MalformedQueryFault_Exception, InvalidQueryLocatorFault_Exception, LoginFault_Exception, IOException {


        BASE64Decoder decoder = new BASE64Decoder();
        byte[] decodedBytes = decoder.decodeBuffer(aService.getInvoiceBody(invoiceid));
        ResponseBuilder response = Response.ok(new ByteArrayInputStream(decodedBytes));
        response.header("Content-Disposition", "attachment; filename=test.pdf");
        return response.build();
}

The service returns a BASE64 encoded string (representing a PDF) that I convert to a byte array (after some google search). I just want the user to see a file download popup with the name 'invoiceid}.pdf' when they click on the link. As of now the response is returned but nothing happens.

Would appreciate any pointers or help here..

Update: Just as a quick test, I disabled the Ajax call and directly called the REST endpoint from the . I was then able to successfully download the file. Perhaps due to some security reasons, this is not achievable through Ajax. Also, I'd like the users to see some kind a 'Please wait' message while this processing happens in the backend. I'd appreciate any inputs on that as well.