Solving PDF Download and Opening Issues Using Ajax
In web development, enabling users to download and open PDF files through an Ajax call can be a challenge. Let's explore a solution that resolves this issue.
In the provided action class (MyAction), a PDF file is generated and its stream is assigned to inputStream. To deliver this stream to the browser, the following Ajax call can be used:
<code class="javascript">$.ajax({ type: "POST", url: url, data: wireIdList, cache: false, success: function(response) { var blob = new Blob([response]); var link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = "<FILENAME_TO_SAVE_WITH_EXTENSION>"; link.click(); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert('Error occurred while opening fax template' + getAjaxErrorString(textStatus, errorThrown)); } });</code>
This updated Ajax call utilizes the Blob() and createObjectURL() methods to create a downloadable file for the browser. The link element is used to trigger the download process and the download attribute specifies the filename to save the PDF as.
By implementing this solution, your Ajax call will successfully download and open the generated PDF file in the browser.
The above is the detailed content of How to Download and Open PDF Files Using Ajax?. For more information, please follow other related articles on the PHP Chinese website!