Home >Web Front-end >JS Tutorial >How to Trigger File Downloads in HTML/JavaScript Without Using Anchors or Server-Side Code?
Question: How can you trigger a file download when clicking an HTML button or executing JavaScript without using anchors, back-end scripts, or modifying server headers?
HTML Method:
The HTML5 download attribute enables file downloads when applied to an anchor tag (). Specify the path to the file and the proposed file name as follows:
<a href="path_to_file" download="proposed_file_name">Download</a>
Restrictions:
Note that the file must reside on the same origin as the page (i.e., same domain, subdomain, protocol, and port). Exceptions include blob:, data:, and file:. Leave the proposed_file_name blank to use the file's actual name.
JavaScript Method:
To trigger a download via JavaScript, you can use the following code:
const downloadElement = document.getElementById("file-request"); downloadElement.addEventListener("click", () => { const link = document.createElement("a"); link.setAttribute("href", "path_to_file"); link.setAttribute("download", "proposed_file_name"); link.click(); });
This code creates a hidden anchor element, sets its download attributes, and simulates a click on it to initiate the download.
Additional Notes:
The above is the detailed content of How to Trigger File Downloads in HTML/JavaScript Without Using Anchors or Server-Side Code?. For more information, please follow other related articles on the PHP Chinese website!