Generally, when you want to download a file from a web application, you must make a request to the server for the file in question so that it can later be downloaded through the user's browser; with a few lines of code and using data URIs it is possible to create files to be downloaded without the need to make this type of requests; the JavaScript code that we will see below allows you to generate a plain text file (TXT) from the content of a text field; specifically from a textarea so it can later be downloaded; First we will see how to create a data URI:
Data URI Syntax
Data URIs allow content to be embedded in small files; Taking an excerpt from the official documentation offered by MDN on data URIs, they comply with the following syntax:
data:[<mediatype>][;base64],<data>
<mediatype> | Allows you to indicate the file type as: Text: Textual (readable) data text such as text/plain (default) or text/html. |
;base64 (optional) | If it is flat or textual data, the text is simply embedded; otherwise you must specify ;base64 to embed binary data such as images or videos. |
The next step indicates the date of the file; example:
data:,Hello%2C%20World!
It corresponds to a plain text file.
Script to generate and download files
The HTML
<textarea id="txt"></textarea>
<a href="#" id="link" download="contenido.txt">Descargar el contenido del textarea</a>
The Javascript
window.onload = function() {
var txt = document.getElementById('txt');
txt.value = window.onload + '';
document.getElementById('link').onclick = function(code) {
this.href = 'data:text/plain;charset=utf-8,'
+ encodeURIComponent(txt.value);
};
};
How does the script to generate and download files work?
The heart of the script:
document.getElementById('link').onclick = function(code) {
this.href = 'data:text/plain;charset=utf-8,'
+ encodeURIComponent(txt.value);
};
The encodeURIComponent() function encodes the text string and embeds it within the link's href attribute for download through the link's download attribute when a click is detected.
Original article: JAVASCRIPT – CREATING A DOWNLOADABLE FILE IN THE BROWSER.
Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter