Home >Web Front-end >JS Tutorial >How to Trigger File Downloads in HTML/JavaScript Without Using Anchors or Server-Side Code?

How to Trigger File Downloads in HTML/JavaScript Without Using Anchors or Server-Side Code?

Barbara Streisand
Barbara StreisandOriginal
2024-12-03 16:35:18343browse

How to Trigger File Downloads in HTML/JavaScript Without Using Anchors or Server-Side Code?

How to Trigger File Downloads Using HTML Buttons or JavaScript

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:

  • Ensure that your server is properly configured to handle file downloads.
  • For more detailed information, refer to the MDN documentation on downloading, HTML Standard on downloading, HTML Standard on download attribute, and CanIUse for browser compatibility.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn