This is crazy but I don\'t know how to do this, and because of how common the words are, it\'s hard to find what I need on search engines. I\'m thinking this should be an ea
Old thread but it's missing a simple js solution:
let a = document.createElement('a')
a.href = item.url
a.download = item.url.split('/').pop()
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
With jQuery:
$("#fileRequest").click(function() {
// // hope the server sets Content-Disposition: attachment!
window.location = 'file.doc';
});
If your looking for a vanilla JavaScript (no jQuery) solution and without using the HTML5 attribute you could try this.
const download = document.getElementById("fileRequest");
download.addEventListener('click', request);
function request() {
window.location = 'document.docx';
}
.dwnld-cta {
border-radius: 15px 15px;
width: 100px;
line-height: 22px
}
<h1>Download File</h1>
<button id="fileRequest" class="dwnld-cta">Download</button>
The solution I have come up with is that you can use download attribute in anchor tag but it will only work if your html file is on the server. but you may have a question like while designing a simple html page how can we check that for that you can use VS code live server or bracket live server and you will see your download attribute will work but if you will try to open it simply by just double clicking html page it open the file instead of downloading it. conclusion: attribute download in anchor tag only works if your html file is no server.
you can add tag without any text but with link. and when you click the button like you have in code , just run the $("yourlinkclass").click() function.
There is a difference between loading a file and downloading a file. The following html code loads a file:
<a href="http://www.fbi.gov/top-secret.pdf">loading on the same tab</a>
After clicking on this link, your current tab will be replaced with the pdf-file that can then be downloaded. On right-clicking on this link, you can choose the menu item save link as for downloading the file directly. If you wish to obtain a save as dialog on clicking on such a link, you might want to take the following code:
<a href="http://www.fbi.gov/top-secret.pdf?download=1">save as...</a>
Your browser will download this file immediately if you choose to use a download directory in your options. Otherwise, your browser will be offering a save as-dialog.
You can also choose a button for downloading:
<button type="submit" onclick="window.open('http://www.fbi.gov/top-secret.pdf?download=1')">
save as...
</button>
If you wish to load the link on a new tab, you take
<a href="http://www.fbi.gov/top-secret.pdf" target="_blank">loading on a new tab</a>
A form element does not heed the directive ?download=1. It only heeds the directive target="_blank":
<form method="get" action="http://www.fbi.gov/top-secret.pdf" target="_blank">
<button type="submit">loading on a new tab</button>
</form>