My Pdf file is stored in google bucket, and i have a link let say https://storage.googleapis.com/bucketName/xyz.pdf. To download this file i am doing this,
<a href="https://storage.googleapis.com/bucketName/xyz.pdf" download> Download This File </a>
But when i click on this anchor tag, instead of downloading this file browser open this file in same tab even i try to download the file via javascript and was using this code .
var link = document.createElement("a");
link.download = 'File.pdf';
link.href = 'https://storage.googleapis.com/bucketName/xyz.pdf';
link.click();
But same happen again file open in same tab instead of downloading. I don't know what is the main problem ? Is this Google bucket is not letting file to download, or my chrome setting preventing files to download.
It is not downloading in Chrome i guess Chrome do allow the downloading from CORS files.
As per JavaScript/jQuery to download file via POST with JSON data construct a blob and use that to return the file reference for the link.
This will inform the browser of your intent in a standards compliance manner.
example ...
$.get(/*...*/,function (result)
{
var blob=new Blob([result]);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="myFileName.txt";
link.click();
});
Solution
Content-Disposition attachment seems to work for me:
self.set_header("Content-Type", "application/json")
self.set_header("Content-Disposition", 'attachment; filename=learned_data.json')
Workaround
application/octet-stream
I had something similar happening to me with a JSON, for me on the server side I was setting the header to
self.set_header("Content-Type", "application/json")
however when i changed it to:
self.set_header("Content-Type", "application/octet-stream")
It automatically downloaded it.
Also know that in order for the file to still keep the .json suffix you will need to it on filename header:
self.set_header("Content-Disposition", 'filename=learned_data.json')
Try link.target = "_blank"; this will open file in new tab and link.download will force it download.
Please tell if this works.
Related
I have a basic idea of HTML. I want to create the download link in my sample website, but I don't have idea of how to create it. How do I make a link to download a file rather than visit it?
In modern browsers that support HTML5, the following is possible:
<a href="link/to/your/download/file" download>Download link</a>
You also can use this:
Download link
This will allow you to change the name of the file actually being downloaded.
This answer is outdated. We now have the download attribute. (see also this link to MDN)
If by "the download link" you mean a link to a file to download, use
Download
the target=_blank will make a new browser window appear before the download starts. That window will usually be closed when the browser discovers that the resource is a file download.
Note that file types known to the browser (e.g. JPG or GIF images) will usually be opened within the browser.
You can try sending the right headers to force a download like outlined e.g. here. (server side scripting or access to the server settings is required for that.)
In addition (or in replacement) to the HTML5's <a download attribute already mentioned,
the browser's download to disk behavior can also be triggered by the following http response header:
Content-Disposition: attachment; filename=ProposedFileName.txt;
This was the way to do before HTML5 (and still works with browsers supporting HTML5).
A download link would be a link to the resource you want to download. It is constructed in the same way that any other link would be:
Link
Link to installer
To link to the file, do the same as any other page link:
link text
To force things to download even if they have an embedded plugin (Windows + QuickTime = ugh), you can use this in your htaccess / apache2.conf:
AddType application/octet-stream EXTENSION
This thread is probably ancient by now, but this works in html5 for my local file.
For pdfs:
<p>test pdf</p>
This should open the pdf in a new windows and allow you to download it (in firefox at least). For any other file, just make it the filename. For images and music, you'd want to store them in the same directory as your site though. So it'd be like
<p><a href="images/logo2.png" download>test pdf</a></p>
There's one more subtlety that can help here.
I want to have links that both allow in-browser playing and display as well as one for purely downloading. The new download attribute is fine, but doesn't work all the time because the browser's compulsion to play the or display the file is still very strong.
BUT.. this is based on examining the extension on the URL's filename!You don't want to fiddle with the server's extension mapping because you want to deliver the same file two different ways. So for the download, you can fool it by softlinking the file to a name that is opaque to this extension mapping, pointing to it, and then using download's rename feature to fix the name.
<a target="_blank" download="realname.mp3" href="realname.UNKNOWN">Download it</a>
<a target="_blank" href="realname.mp3">Play it</a>
I was hoping just throwing a dummy query on the end or otherwise obfuscating the extension would work, but sadly, it doesn't.
You can use in two ways
<a href="yourfilename" download>Download</a>
it will download file with original name In Old Browsers this option was not available
2nd
Download
Here You have option to rename your file and download with a different name
The download attribute is new for the <a> tag in HTML5
<a href="http://www.odin.com/form.pdf" download>Download Form</a>
or
Download Form
I prefer the first one it is preferable in respect to any extension.
If you host your file in AWS, this may work for you. The code is very easy to understand. Because the browser doesn't support same-origin download links, 1 way to solve it is to convert the image URL to a base64 URL. Then, you can download it normally.
var canvas = document.createElement("canvas")
var ctx = canvas.getContext('2d')
var img = new Image()
img.src = your_file_url + '?' + new Date().getTime();
img.setAttribute('crossOrigin', '')
var array = your_file_url.src.split("/")
var fileName = array[array.length - 1]
img.onload = function() {
canvas.width = img.naturalWidth
canvas.height = img.naturalHeight
ctx.drawImage(img,
0, 0, img.naturalWidth, img.naturalHeight,
0, 0, canvas.width, canvas.height)
var dataUrl = canvas.toDataURL("image/png", 1)
var a = document.createElement('a')
a.href = dataUrl
a.download = fileName
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
Like this
Link name
So a file name.jpg on a site example.com would look like this
Image
i know i am late but this is what i got after 1 hour of search
<?php
$file = 'file.pdf';
if (! file) {
die('file not found'); //Or do something
} else {
if(isset($_GET['file'])){
// Set headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
// Read the file from disk
readfile($file); }
}
?>
and for downloadable link i did this
Download PDF
I have a basic idea of HTML. I want to create the download link in my sample website, but I don't have idea of how to create it. How do I make a link to download a file rather than visit it?
In modern browsers that support HTML5, the following is possible:
<a href="link/to/your/download/file" download>Download link</a>
You also can use this:
Download link
This will allow you to change the name of the file actually being downloaded.
This answer is outdated. We now have the download attribute. (see also this link to MDN)
If by "the download link" you mean a link to a file to download, use
Download
the target=_blank will make a new browser window appear before the download starts. That window will usually be closed when the browser discovers that the resource is a file download.
Note that file types known to the browser (e.g. JPG or GIF images) will usually be opened within the browser.
You can try sending the right headers to force a download like outlined e.g. here. (server side scripting or access to the server settings is required for that.)
In addition (or in replacement) to the HTML5's <a download attribute already mentioned,
the browser's download to disk behavior can also be triggered by the following http response header:
Content-Disposition: attachment; filename=ProposedFileName.txt;
This was the way to do before HTML5 (and still works with browsers supporting HTML5).
A download link would be a link to the resource you want to download. It is constructed in the same way that any other link would be:
Link
Link to installer
To link to the file, do the same as any other page link:
link text
To force things to download even if they have an embedded plugin (Windows + QuickTime = ugh), you can use this in your htaccess / apache2.conf:
AddType application/octet-stream EXTENSION
This thread is probably ancient by now, but this works in html5 for my local file.
For pdfs:
<p>test pdf</p>
This should open the pdf in a new windows and allow you to download it (in firefox at least). For any other file, just make it the filename. For images and music, you'd want to store them in the same directory as your site though. So it'd be like
<p><a href="images/logo2.png" download>test pdf</a></p>
There's one more subtlety that can help here.
I want to have links that both allow in-browser playing and display as well as one for purely downloading. The new download attribute is fine, but doesn't work all the time because the browser's compulsion to play the or display the file is still very strong.
BUT.. this is based on examining the extension on the URL's filename!You don't want to fiddle with the server's extension mapping because you want to deliver the same file two different ways. So for the download, you can fool it by softlinking the file to a name that is opaque to this extension mapping, pointing to it, and then using download's rename feature to fix the name.
<a target="_blank" download="realname.mp3" href="realname.UNKNOWN">Download it</a>
<a target="_blank" href="realname.mp3">Play it</a>
I was hoping just throwing a dummy query on the end or otherwise obfuscating the extension would work, but sadly, it doesn't.
You can use in two ways
<a href="yourfilename" download>Download</a>
it will download file with original name In Old Browsers this option was not available
2nd
Download
Here You have option to rename your file and download with a different name
The download attribute is new for the <a> tag in HTML5
<a href="http://www.odin.com/form.pdf" download>Download Form</a>
or
Download Form
I prefer the first one it is preferable in respect to any extension.
If you host your file in AWS, this may work for you. The code is very easy to understand. Because the browser doesn't support same-origin download links, 1 way to solve it is to convert the image URL to a base64 URL. Then, you can download it normally.
var canvas = document.createElement("canvas")
var ctx = canvas.getContext('2d')
var img = new Image()
img.src = your_file_url + '?' + new Date().getTime();
img.setAttribute('crossOrigin', '')
var array = your_file_url.src.split("/")
var fileName = array[array.length - 1]
img.onload = function() {
canvas.width = img.naturalWidth
canvas.height = img.naturalHeight
ctx.drawImage(img,
0, 0, img.naturalWidth, img.naturalHeight,
0, 0, canvas.width, canvas.height)
var dataUrl = canvas.toDataURL("image/png", 1)
var a = document.createElement('a')
a.href = dataUrl
a.download = fileName
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
Like this
Link name
So a file name.jpg on a site example.com would look like this
Image
i know i am late but this is what i got after 1 hour of search
<?php
$file = 'file.pdf';
if (! file) {
die('file not found'); //Or do something
} else {
if(isset($_GET['file'])){
// Set headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
// Read the file from disk
readfile($file); }
}
?>
and for downloadable link i did this
Download PDF
I have an amazon S3 URL being passed back to me from an external service that is in the format:
https://foo.s3.amazonaws.com/ProjectDownloads/foo/title.xlsx?AWSAccessKeyId=foo&Expires=1602279238&Signature=foo
I haven't worked much with S3, but my understanding is this is a Presigned URL - I can paste it in my browser and the excel file downloads.
How can I download this file directly using javascript (on the frontend, as my system is not running node)?
I have tried generating an tag element with click - however all my files download as corrupt. I can download the file directly by pasting the link in my browser and it auto initiates a download.
Any help will be appreciated.
I have tried the following, but it downloads a file with error:
var link = document.createElement('a');
link.href = url;
link.download = 'foo.xlsx';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
You don’t need JS to force a download on clicking the link; you can do this with just HTML. And, it doesn’t matter that the source is a presigned S3 URL - it works with any URL.
<a href=“Foo.xlsx” download>click to download</a> should do it for you.
Have a look at https://www.w3schools.com/howto/howto_html_download_link.asp for the browser support matrix.
I have a Javascript function that basically force downloads a file once provided the URL and name of the file. This function works absolutely fine as intended I call it from a HTML tag/hyperlink. But once the MP3 file from my function downloads it wont play on my computer. I have designed this function for a user to be able to download different MP3 and WAV files upon clicking on the associated link for that file. I can only play the downloaded MP3 file on the media player VLC it won't play on my laptop. Is there something I am doing to the MP3 file in the download process with my function or why will it not play once downloaded?
I have looked into MP3 file variations and encoding but Im not sure what to look for really or what I am doing wrong. When I download MP3 files from other sites they are working fine and play straight away.
Function:
<script>// <![CDATA[
function downloadFile(data, fileName, type="text/plain") {
// Create an invisible A element
const a = document.createElement("a");
a.style.display = "none";
document.body.appendChild(a);
// Set the HREF to a Blob representation of the data to be downloaded
a.href = window.URL.createObjectURL(
new Blob([data], { type })
);
// Use download attribute to set set desired file name
a.setAttribute("download", fileName);
// Trigger the download by simulating click
a.click();
// Cleanup
window.URL.revokeObjectURL(a.href);
document.body.removeChild(a);
}
// ]]></script>
Function Call:
My Download
If you look in the downloaded file, you'll find it contains the text https://cdn.shopify.com/s/files/1/0037/4951/1217/files/ascence-places-like-that-ncs-release.mp3?360 because that's the value you're passing for data and using when creating the blob. Nothing about that code creating a blob downloads the content (and the SOP prevents your code from downloading the content, unless of course the other site overrides it with CORS).
I don't think you can force the link to open the Save dialog. Normally that's triggered by the response to the link from the server (via the Content-Disposition header), which of course you can't control in your scenario. Using the download attribute won't do it, it has no effect cross-origin (other than when the link is a data: or blob: URL, see MDN's description).
You can show them the link so they can right-click and choose "Save target as...", but I know that's going to be a disappointing answer for you.
I have a blob url and a button on my site. The user can click on that button and the blob opens in a new tab.
<a class="downloadlink" id="downloadlink" target="_blank" href="[[_blobUrl]]"></a>
This works.
If the user has the setting for the file type behind this blob (e.g. pdf) to save the file instead of previewing it in the browser, the file gets downloaded of course. But firefox creates a random filename of the format
[a-zA-Z0-9]{8}\.pdf
Chrome uses the blob uuid and appends pdf.
How can I control the filename AND respect the users preferences?
When I add the download attribute the file gets always downloaded, also when the user has the setting "Preview" for the specified file type. I want the behavior the user prefers (preview or download) but still control the filename in case the user prefers downloading the file.
Update for firefox:
I got a solution for firefox but it is not working in chrome. Instead of
this._blobUrl = URL.createObjectURL(blob);
I do
let file = new File([blob], this.downloadname, {type: 'application/pdf'});
this._blobUrl = URL.createObjectURL(file);
Chrome does expose this preference through the navigator.plugins dictionary. If this object contains a PDF Reader, then you know the user wants to see it displayed in their browser.
const opensInBrowser = [...navigator.plugins].some(plug => [...plug].some(mime => mime.type === 'application/pdf'))
console.log(opensInBrowser);
But this does only work for Chrome. Firefox doesn't expose this information here (IIRC they don't technically use a Plugin to display the pdf). So this means that we can't use only this; Firefox will always be marked as not opening in browser, while it may very well be.
So I think the only way is still a very long one... exposed in details here..
Using a Service Worker, we can fake a request to a named file, that Chrome will use to set the name, both of the downloaded file and of the pdf read by the plugin.
That is until they follow Firefox in forwarding correctly File objects names through the Blob URIs that point to them.
Simpliest solution (that should also work with IE10) is to create an a element, attach it to body, set it's name, let user download it and remove after, something like this:
function save(){
const file = new File(['this is where BLOB should go'], {type: 'application/pdf'}); // edit this line to have access to source blob
const link = document.createElement('a');
link.href = URL.createObjectURL(file);
link.download = 'this is the name.pdf';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
window.save = save;
and for HTML:
<a class="downloadlink" id="downloadlink" target="_blank" onclick='save()'>here is your link</a>
working example can be found here
take notice of:
you should edit the onclick function to pass the blob you're
expecting to be as an output of the file
in example i created a pdf only, however you can extend this
functionality pretty easily to any kind of document you need (and is
recognizable by given browser)