How to make a browser display a "save as dialog" so the user can save the content of a string to a file on his system? How to make a browser display a "save as dialog" so the user can save the content of a string to a file on his system? javascript javascript

How to make a browser display a "save as dialog" so the user can save the content of a string to a file on his system?


In case anyone is still wondering...

I did it like this:

<a href="data:application/xml;charset=utf-8,your code here" download="filename.html">Save</a>

can't remember my source but it uses the following techniques\features:

  1. html5 download attribute
  2. data URI's

Found the reference:

http://paxcel.net/blog/savedownload-file-using-html5-javascript-the-download-attribute-2/


EDIT:As you can gather from the comments, this does NOT work in

  1. Internet Explorer (however works in Edge v13 and later)
  2. Opera Mini

http://caniuse.com/#feat=download


There is a javascript library for this, see FileSaver.js on Github

However the saveAs() function won't send pure string to the browser, you need to convert it to blob:

function data2blob(data, isBase64) {  var chars = "";  if (isBase64)    chars = atob(data);  else    chars = data;  var bytes = new Array(chars.length);  for (var i = 0; i < chars.length; i++) {    bytes[i] = chars.charCodeAt(i);  }  var blob = new Blob([new Uint8Array(bytes)]);  return blob;}

and then call saveAs on the blob, as like:

var myString = "my string with some stuff";saveAs( data2blob(myString), "myString.txt" );

Of course remember to include the above-mentioned javascript library on your webpage using <script src=FileSaver.js>


There is a new spec called the Native File System API that allows you to do this properly like this:

const result = await window.chooseFileSystemEntries({ type: "save-file" });

There is a demo here, but I believe it is using an origin trial so it may not work in your own website unless you sign up or enable a config flag, and it obviously only works in Chrome. If you're making an Electron app this might be an option though.