Home >Web Front-end >JS Tutorial >How to Trigger File Downloads Using Only HTML Buttons or JavaScript?

How to Trigger File Downloads Using Only HTML Buttons or JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-12-01 04:24:15553browse

How to Trigger File Downloads Using Only HTML Buttons or JavaScript?

Triggering File Downloads with HTML Buttons or JavaScript

Question:

How can you initiate a file download when clicking an HTML button without using anchor tags, backend scripts, or server configurations?

HTML Button Solution:

You can use the download attribute to trigger a file download:

where:

  • myfile.txt is the desired filename
  • The file URL must be on the same origin (domain, protocol, etc.)

JavaScript Solution:

To download a file via JavaScript, you can use the Blob and URL APIs:

where:

  • data is the file data
  • 'text/plain' is the file type
  • myfilename.txt is the desired filename

The above is the detailed content of How to Trigger File Downloads Using Only HTML Buttons or JavaScript?. 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