Home >Web Front-end >JS Tutorial >How to Trigger File Downloads Using HTML Buttons or JavaScript?
Triggering File Downloads from HTML Buttons or JavaScript
In web development, it's often necessary to provide users with the ability to download files. While the traditional HTML anchor tag with a href attribute is often used for this purpose, you may encounter situations where you want to trigger the download using a button or JavaScript.
Method 1: Using HTML5 Download Attribute
To trigger a file download using an HTML button, you can employ the HTML5 download attribute. This attribute specifies the filename to be used when saving the file and works with both and
<button type="button" download="file.doc">Download!</button>
Method 2: Triggering Download via JavaScript
You can also trigger a file download programmatically using JavaScript. However, this method requires a slightly different approach. Instead of using the href attribute, you can set the location.href property of the window object to the file's URL and add the filename to the download attribute of the a element.
$("#fileRequest").click(function() { location.href = "file.doc"; $("a").attr("download", "proposed_file_name"); });
Additional Considerations
The above is the detailed content of How to Trigger File Downloads Using HTML Buttons or JavaScript?. For more information, please follow other related articles on the PHP Chinese website!