TheRogerLAB Codes

Create and download a text file

  July, 2021

Introduction

Generate a text report, not from the server but from our browser. Is it possible? Yes, and it can be done using javascript as follow:

Step 1: Define a button in HTML

<button onclick='createFile()'>Create</button>

Step 2: Define a function to create and download

function createFile(){
  //create or obtain the file's content
  var content = 'This is a text';

  //create a file and put the content, name and type
  var file = new File(["\ufeff"+content], 'myFile.txt', {type: "text/plain:charset=UTF-8"});

  //create a ObjectURL in order to download the created file
  url = window.URL.createObjectURL(file);

  //create a hidden link and set the href and click it
  var a = document.createElement("a");
  a.style = "display: none";
  a.href = url;
  a.download = file.name;
  a.click();
  window.URL.revokeObjectURL(url);

Check a working demo for this code:

SEE DEMO WATCH VIDEO RATE THIS ARTICLE
4.8
6
TheRogerLAB Codes
Powered by TheRogerLAB Sandbox

info@therogerlab.com