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.
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).
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>
$.ajax({ url: '<URL_TO_FILE>', success: download.bind(true, "<FILENAME_TO_SAVE_WITH_EXTENSION>", "<FILE_MIME_TYPE>") });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With