Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download and open PDF file using Ajax

I have an action class that generates a PDF. The contentType is set appropriately.

public class MyAction extends ActionSupport  {    public String execute() {     ...     ...     File report = signedPdfExporter.generateReport(xyzData, props);      inputStream = new FileInputStream(report);     contentDisposition = "attachment=\"" + report.getName() + "\"";     contentType = "application/pdf";     return SUCCESS;    } } 

I call this action through an Ajax call. I don't know the way to deliver this stream to browser. I tried a few things but nothing worked.

$.ajax({     type: "POST",     url: url,     data: wireIdList,     cache: false,     success: function(response)     {         alert('got response');         window.open(response);     },     error: function (XMLHttpRequest, textStatus, errorThrown)      {         alert('Error occurred while opening fax template'                + getAjaxErrorString(textStatus, errorThrown));     } }); 

The above gives the error:

Your browser sent a request that this server could not understand.

like image 262
Nayn Avatar asked Jan 04 '10 13:01

Nayn


People also ask

How can download PDF with button click in jQuery?

Downloading PDF File on Button Click using jQueryInside the DownloadFile JavaScript function, the URL of the File is passed as parameter to the jQuery AJAX function. Inside the jQuery AJAX function, using the XmlHttpRequest (XHR) call, the PDF file is downloaded as Byte Array (Binary Data).


1 Answers

Here is how I got this working

$.ajax({   url: '<URL_TO_FILE>',   success: function(data) {     var blob=new Blob([data]);     var link=document.createElement('a');     link.href=window.URL.createObjectURL(blob);     link.download="<FILENAME_TO_SAVE_WITH_EXTENSION>";     link.click();   } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Updated answer using download.js

$.ajax({   url: '<URL_TO_FILE>',   success: download.bind(true, "<FILENAME_TO_SAVE_WITH_EXTENSION>", "<FILE_MIME_TYPE>") });
like image 200
Mayur Padshala Avatar answered Oct 03 '22 08:10

Mayur Padshala