Reputation: 99
Situation:
Current solution:
I cannot replace the button with the simple <a href="url" download>
because the URL is generated in response to user's request and it is not known in advance.
I want it to be a one-click experience (i.e., I don't want the user to click a new button with the received URL).
Question:
window.location
for that purpose?Upvotes: 1
Views: 2492
Reputation: 21
Just open a new tab:
window.open(downloadUrl, "_blank");
This way the browser starts downloading the file, then the new tab will be automatically closed.
Temporary inject the hidden form into your current page, then submit it:
var form = $('<form action="' + downloadUrl + '" method="POST" target="_blank">'
+ '<input name="param1" value="value1" />'
+ '</form>');
form.appendTo(document.body);
$(form).submit();
form.remove();
The key here is target="_blank" form's attribute. For today, Chrome will automatically close the new tab, while Safari is not. But both download the file.
Upvotes: 0
Reputation: 179084
This is actually a very simple problem that needs no Javascript at all.
When the request is sent to the server by simply clicking a link to make the request, the server -- after validating the request, generates a signed URL, then responds...
HTTP/1.1 302 Found
Location: https://example-bucket.s3.amazonaws.com/... # new signed URL
The browser follows the redirect and fetches the resource.
Upvotes: 0
Reputation: 349
Right way is make backend send proper Content-Type
header with correct MIME type of file on link download request.
It is ok to change window.location
or document.location.href
for page redirect to download link.
Upvotes: 0
Reputation: 8315
It not sound right to change window.location
for download file..
If you using a <a>
tag you can add the download
attribute
<a href="my.pdf" download="your.pdf" >download file</a>
If you prefer using code, you can use script like this:
var aTag = document.createElement('a');
aTag.setAttribute('download','your.pdf');
aTag.setAttribute('href','my.pdf');
aTag.click();
Upvotes: 1