How to Download a File Without Using ≪A≫ Element With Download Attribute or a Server

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

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>

Download attribute opens file instead of downloading

Your code is correct, however, the download attribute only works when you are viewing the code from a server, due to the same-origin policy of most browsers.

Are you previewing the file by double-clicking the file or directly opening it up in a browser? If the URL while previewing starts with something similar to file://FILEPATH_HERE or /Users/FILEPATH_HERE, you are opening the file rather than serving the file. If so, you should run your code from within a localhost setup to test. That may involve running a server locally, or using an editor extension to spin up a project-based server. Once your URL starts with http:// or https:// the download will work as intended.

Alternatively, you could upload the project somewhere on the web.

How to trigger a file download when clicking an HTML button or JavaScript

For the button you can do

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

Download File Using JavaScript/jQuery

Use an invisible <iframe>:

<iframe id="my_iframe" style="display:none;"></iframe>
<script>
function Download(url) {
document.getElementById('my_iframe').src = url;
};
</script>

To force the browser to download a file it would otherwise be capable of rendering (such as HTML or text files), you need the server to set the file's MIME Type to a nonsensical value, such as application/x-please-download-me or alternatively application/octet-stream, which is used for arbitrary binary data.

If you only want to open it in a new tab, the only way to do this is for the user to a click on a link with its target attribute set to _blank.

In jQuery:

$('a#someID').attr({target: '_blank', 
href : 'http://localhost/directory/file.pdf'});

Whenever that link is clicked, it will download the file in a new tab/window.



Related Topics



Leave a reply



Submit