How to download a pdf in ajax?

0

I have a method that returns a pdf

return File(stream, "application/pdf");

I call this method with ajax in the following way

  $.ajax({
        url: '@Url.Action("HojaDeSalidaPDF")',
        data: { 'ID': id },
        type: "GET",
        contentType: 'application/json; charset=utf-8',
        success: function (data) {

            //Descargar PDF

        },
        error: function (xhr, status, thrownError) {
            onFailure(xhr, status, thrownError);
        }
    });

My question is how can I do it so that I can download the pdf?

    
asked by mvega 28.01.2017 в 19:30
source

1 answer

0

A fairly easy solution is to add a link to that file and call it, this function is an example of how to do it.

We create an a with link to the file (in the example it is a link where we pass the data, that is, we could make a "data: image, base64" and send to download an image that we have in base64 in some variable, etc), then the name of the file. We add it to the sun, we force its click and remove it from the DOM. Easy and for the whole family.

function descargarArchivo(uri, name) {
  var link = document.createElement("a");
  link.download = name;
  link.href = uri;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  delete link;
}

descargarArchivo("data:text/html,HelloWorld!", "helloWorld.txt");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Example example taken from the answer: link

    
answered by 28.01.2017 в 20:00