Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download a file without using <a> element with download attribute or a server?

According to caniuse the download attribute of <a> element is supported at Microsoft Edge build 10547+, but not IE or Safari.

How to download a file object without using <a> element with download attribute set or a server?

like image 751
guest271314 Avatar asked Aug 02 '16 04:08

guest271314


People also ask

How do you make a file downloadable in HTML?

The “download” attribute is used to make the link downloadable. It will specify the target (pdf, zip, jpg, doc, etc) that will be downloaded only when the user clicks on the link. Note: The download attribute can be only used when the href attribute is set before.

Why download attribute is not working in HTML?

The download attribute only works for same-originl URLs. So if the href is not the same origin as the site, it won't work. In other words, you can only download files that belongs to that website. This attribute follows the same rules outline in the same-origin policy.

How do I force download a link instead of open?

In most browsers, clicking on the link will open the file directly in the browser. But, if you add the download attribute to the link, it will tell the browser to download the file instead. The download attribute works in all modern browsers, including MS Edge, but not Internet Explorer.


2 Answers

There are a number of ways of triggering a download. Following are a few:

Use a form:

<form method="get" action="mydoc.doc">
<button type="submit">Download</button>
</form>

Use javascript:

<button type="submit" onclick="window.open('mydoc.doc')">Download</button>
like image 68
Leo Farmer Avatar answered Oct 25 '22 08:10

Leo Farmer


Although I support @LeoFarmer's answer, I would like to offer two "hackable" approaches:

  1. If the file is very small, you can use a with the href='data:[<mediatype>][;base64],<data>'.

    This could allow you to add content disposition in the mediatype, emulating an HTTP header. This hack is also not as portable as one might hope.

  2. On small to medium files, it's possible to download the file using AJAX, and then use the Javascript File API to prompt for file saving (the API doesn't support saving, but it's easy to convert the data to a data URL).

    If you want to avoid the Javascript File API, you can try emulating an anchor click, as suggested here.

Again, as pointed out by Leo Farmer, these solutions can't promise that the browser won't open the file in a new tab instead of saving it to the disk, but I think it's safe to say that all users will be able to gracefully degrade to a cmd+S or ctrl+S keyboard shortcut :-)

like image 27
Myst Avatar answered Oct 25 '22 09:10

Myst