Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 can I make a browser display a "save as dialog" so the user can save the content of a string to a file on his system?

For example:

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

Resulting in something like this:

Example

like image 474
MaiaVictor Avatar asked Jul 05 '12 00:07

MaiaVictor


People also ask

How do I display Save As dialog box?

Use the shortcut F12 to display the Save As dialog box in Excel. Press CTRL + s to save an existing workbook. It's good practice to periodically save while you are working on your Excel file.

How do I save a dialog?

To save a file using the SaveFileDialog component. Display the Save File dialog box and call a method to save the file selected by the user. Use the SaveFileDialog component's OpenFile method to save the file. This method gives you a Stream object you can write to.

Which method is used to open Save dialog?

By pressing F12, Save As dialogue box will open.


6 Answers

EDIT 2022: Please see other answers regarding File System API


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

like image 166
Craig Wayne Avatar answered Oct 10 '22 02:10

Craig Wayne


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.

like image 31
Timmmm Avatar answered Oct 10 '22 01:10

Timmmm


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>

like image 25
Tomas M Avatar answered Oct 10 '22 00:10

Tomas M


This is possible using this cross browser javascript implementation of the HTML5 saveAs function: https://github.com/koffsyrup/FileSaver.js

If all you want to do is save text then the above script works in all browsers(including all versions of IE), using nothing but JS.

like image 43
superphonic Avatar answered Oct 10 '22 00:10

superphonic


Solution using only javascript

function saveFile(fileName,urlFile){
    let a = document.createElement("a");
    a.style = "display: none";
    document.body.appendChild(a);
    a.href = urlFile;
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(url);
    a.remove();
}

let textData = `El contenido del archivo
que sera descargado`;
let blobData = new Blob([textData], {type: "text/plain"});
let url = window.URL.createObjectURL(blobData);
//let url = "pathExample/localFile.png"; // LocalFileDownload
saveFile('archivo.txt',url);
like image 31
Ronald Coarite Avatar answered Oct 10 '22 02:10

Ronald Coarite


Using showSaveFilePicker():

const handle = await showSaveFilePicker({
    suggestedName: 'name.txt',
    types: [{
        description: 'Text file',
        accept: {'text/plain': ['.txt']},
    }],
});

const blob = new Blob(['Some text']);

const writableStream = await handle.createWritable();
await writableStream.write(blob);
await writableStream.close();
like image 33
Richie Bendall Avatar answered Oct 10 '22 01:10

Richie Bendall