To trigger a file download on a button click we will use a custom function or HTML 5 download attribute.
Approach 1: Using Download attribute
The download attribute simply uses an anchor tag to prepare the location of the file that needs to be downloaded. The name of the file can be set using the attribute value name, if not provided then the original filename will be used.
filename: attribute specifies the name for the file that will be downloaded.
- firstly made a textarea where all the text input will be issued.
- make an anchor tag using createElement property and then assigning it the download and href attribute.
- encodeURIComponent will encode everything with special meaning, so you use it for components of URIs.
For example, if we have text like “Hello: Geek ?”, there are special characters in this, so encodeURIComponent will encode them and append it for further usage.
- data:text/plain; charset=utf-8 is the attribute value of href (like href=” “), it specifies that the value must be of type text and with UTF-8 type encoding. The click() method simulates a mouse-click on an element.
- After that we simply call our download function with the text from textarea and our file name “GFG.txt” as parameters on the input button with id ‘btn’.
- How to change the button color after clicking it using AngularJS ?
- Download file from URL using PHP
- How to download a CSV file in PHP that is triggered through a URL ?
- How to avoid dropdown menu to close menu items on clicking inside ?
- How to make a Bootstrap 4 accordion collapse when clicking the whole header div ?
- jQuery | trigger() Method
- How to trigger onchange event on input type=range while dragging in Firefox ?
- Difference between Trigger and Procedure in DBMS
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : polokghosh53