JAX-RS | Download PDF from Base64 encoded data

People,

I have a REST controller that calls a service to get a BASE 64 encoded string that is a PDF. I am calling my REST endpoint via an AJAX call. I basically want the user to actually download the PDF when they click on the 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), which I convert to a byte array (after some googling). I just want the user to see a popup of downloading a file named "invoiceid" .pdf "when they click on the link. At the moment, the response comes back but nothing happens.

Would appreciate any pointers or help here.

Update. As a quick test, I disabled the Ajax call and called the REST endpoint directly. Then I was able to download the file successfully. Perhaps due to some security reasons this is not possible for Ajax. Also, I would like users to see some kind of "Please wait" message while this processing is happening in the backend. I would appreciate any input on this.

+1


source to share





All Articles