0

I'd like to open my js file genereted by a microservice (byte[]):

 public int getLabel(Request request, Response response) throws      IOException {
        response.header("Access-Control-Allow-Origin", "*");
        ArrayList<JSONObject> orders = createListOfJSONObjects(request.queryParams("orders"));
        response.header("Content-Type", "application/pdf");
        ServletOutputStream outputStream = response.raw().getOutputStream();
        outputStream.write(createPDF(orders));
        outputStream.flush();
        outputStream.close();

        return 200;
    }

I'd like to have the response by ajax:

$("#printlabels").click(function() {
        var jsonData = $(this).data().ordersJson;
        console.log(jsonData)
        $.ajax({
            // type: GET,
            async: true,
            url: "http://localhost:60000/api/create-label",
            data: {orders: jsonData},
            success: function(resp){
                ???;
            }

        });
    });

I want my browser to open or save the pdf file

krtsz
  • 75
  • 8
  • Better to change data of PDF file into a base64 encoded string in API. After that, in frontend, you can use PDF.js to decode that string data into PDF file binary. (Possible discuss for it: http://stackoverflow.com/questions/12092633/pdf-js-rendering-a-pdf-file-using-a-base64-file-source-instead-of-url) – IzumiSy Jan 18 '17 at 13:08

1 Answers1

0

Don't use ajax, try this:

$("#printlabels").click(function() {
    var jsonData = $(this).data().ordersJson;

    var url = "http://localhost:60000/api/create-label";
    var $form = $('<form method="get" action="' + url + '" target="_blank" />');

    for ( var key in jsonData ) {
        $form.append('<input type="hidden" name="' + key + '" value="' + jsonData[key] + '" /> ');
    }

    $form.submit();
});

Read this why you cannot do this with ajax: https://stackoverflow.com/a/9821924/5611328

Community
  • 1
  • 1
er-han
  • 1,859
  • 12
  • 20