Home > Java > javaTutorial > body text

How to Download and Open PDF Files Using Ajax?

DDD
Release: 2024-10-31 02:14:29
Original
213 people have browsed it

How to Download and Open PDF Files Using Ajax?

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!