Adrian
Adrian

Reputation: 2012

How to download URL instead of opening it with JavaScript

I'm creating a PDF and outputting it using Ajax

Here is the output on success:

window.location.replace(json['download_link']);

However, I want to prompt a download instead of opening up the file itself. Is it this straightforward?

Upvotes: 0

Views: 410

Answers (1)

Dehli
Dehli

Reputation: 5960

Add this to your html where you want the download link to appear.

<a download="file" id="downloadlink" style="display: none">Download</a>

Then in your success add the following.

// Get the hidden download link
var link = document.getElementById('downloadlink');
// Set the link to the json response
link.href = json['download_link'];
// Unhide the link
link.style.display = 'block';

Upvotes: 2

Related Questions