Atul Jain
Atul Jain

Reputation: 1085

Download PDF from Byte array using ajax

I am trying below code but this is creating file but not showing content. I need your anyone help, What i am doing wrong.

    $.ajax({
    type: "POST",
    async : false,
    url: "/searchModel/createPDF",
    data:"my_param",
    contentType: 'application/octet-stream',  
    beforeSend:function(){

    }, 
    success: function(html) {
        /* html value is [37,80,68,75 .........] */
        //var file = new Blob([html], {type: 'application/pdf'});
        //var fileURL = URL.createObjectURL(file);
        //window.open(fileURL);

        var blob=new Blob([html],{type: 'application/pdf'});
        var link=document.createElement('a');
        link.href=window.URL.createObjectURL(blob);
        link.download="SearchedResults.pdf";
        link.click();

    }
 }); 

Response coming from server is in byte array [37,80,68,75 .........]

Please help me if data in bytes array how it would be convert in pdf.

Upvotes: 2

Views: 14978

Answers (2)

Atul Jain
Atul Jain

Reputation: 1085

Yes you people said correct does not mean while download PDF using AJAX.

 window.location = "/searchModel/createPDF?" + "my_param";

is enough,Only we need to render pdf from server side. It is default downloadable.Thanks for your suggestions

Upvotes: 0

Kishore Sahasranaman
Kishore Sahasranaman

Reputation: 4230

You cannot use AJAX to download files. It doesn't make sense. You can send the AJAX request and fetch the file contents inside the success handler on the client, but for obvious security reasons you can't do much with it. You cannot save it on the client computer and there's no javascript API allowing you to prompt the user where to save it.

So to download files, don't use AJAX. Create an anchor pointing to your server side script that serves the file to be downloaded.

Sample :

window.downloadfile = function(e){
  window.location = "/searchModel/createPDF?" +  "my_param";
}
<a href="#" onclick="downloadfile()">download file</a>

Upvotes: 1

Related Questions