How To Send PDF File To Frontend?
Solution 1:
I think the main reason this isn't working for you is because jQuery doesn't support the 'blob' data type.
I did some research and found an example of how to get this to work with jQuery:
http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/
You need to include the jQuery plugin from the blog post then convert your $.post call to a $.ajax call (with method POST) and specify that the transfer data type be 'binary' (to load the plugin).
After including the plugin, change your code to look like this:
$.ajax({
method: "POST",
url: "/someroute",
dataType: 'binary' // USE THE PLUGIN
})
.then(function (data) {
console.log("Got the PDF file!");
// Do with the PDF data as you please.
var downloadLink = document.createElement('a')
downloadLink.target = '_blank'
downloadLink.download = 'new_pdf_haha.pdf'
var blob = new Blob([data], { type: 'application/pdf' })
var URL = window.URL || window.webkitURL
var downloadUrl = URL.createObjectURL(blob)
downloadLink.href = downloadUrl
document.body.append(downloadLink) // THIS LINE ISN'T NECESSARY
downloadLink.click()
document.body.removeChild(downloadLink); // THIS LINE ISN'T NECESSARY
URL.revokeObjectURL(downloadUrl);
})
.catch(function (err) {
console.error("An error occurred.");
console.error(err);
});
There's a full working example for you here:
https://github.com/ashleydavis/pdf-server-example
Note that my server setup is different to yours, that may or may not be an issue for you. I have included example code for streaming and non-streaming PDF file download for comparison - streaming is used by default because I think that's what you wanted.
Also note that it does not appear necessary to add your synthesized link to the document and I have marked those lines as unnecessary.
I should also note that it is probably best to do this kind of thing with HTTP GET rather than HTTP POST. If you did that you could simplify your browser download code to be the following:
var downloadLink = document.createElement('a');
downloadLink.target = '_blank';
downloadLink.download = 'new_pdf_haha.pdf';
downloadLink.href = "someroute";
document.body.append(downloadLink)
downloadLink.click()
document.body.removeChild(downloadLink);
Post a Comment for "How To Send PDF File To Frontend?"