Home > Java > javaTutorial > How to Download PDFs with Ajax: A Simple Solution

How to Download PDFs with Ajax: A Simple Solution

Susan Sarandon
Release: 2024-10-29 04:02:29
Original
366 people have browsed it

How to Download PDFs with Ajax: A Simple Solution

Managing PDF Downloads with Ajax

Encountering roadblocks when attempting to deliver PDF streams via Ajax calls can be frustrating. This article explores a solution to this challenge.

In the presented code, an action class generates a PDF and sets the appropriate content type. However, the approach used to deliver the stream to the browser via Ajax encounters an error.

The error arises because the Ajax response is not handled correctly. To resolve this, we can modify the success function in the Ajax request as follows:

<code class="js">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();
}</code>
Copy after login

This script creates a blob object based on the received data, constructs an anchor element (), sets its href attribute to the URL of the blob, and sets its download attribute to the desired filename. By clicking this anchor element, the browser triggers the download process for the PDF.

The above is the detailed content of How to Download PDFs with Ajax: A Simple Solution. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template