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

184006 次浏览

编辑2022: 请参阅有关文件系统 API 的其他答案


如果还有人想知道..。

我是这样做的:

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

我不记得我的来源,但它使用以下技术特点:

  1. Html5下载属性
  2. 数据 URI 的

找到参考资料了:

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


编辑: As you can gather from the comments, this does 没有 work in

  1. Internet Explorer (不过可以在 Edge v13及更高版本中使用)
  2. 迷你歌剧

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

这里有一个 javascript 库,请参阅 Github 上的 FileSaver.js

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;
}

然后调用 saveAs,就像这样:

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

当然,记住使用 <script src=FileSaver.js>在你的网页上包含上面提到的 javascript 库

使用 HTML5saveAs函数的这种跨浏览器的 javascript 实现是可能的: 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.

有一个新的规格称为 Native File System API,它允许你像 这个一样正确地做这件事:

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

有一个演示 给你,但我相信它是使用原始试用版,所以它可能无法在您自己的网站,除非您注册或启用配置标志,它显然是 only works in Chrome。如果你正在制作一个电子应用程序,这可能是一个选择。

只使用 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);

使用 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();

受到 @ Ronald-coarite答案的启发,以下是我的解决方案:

function saveTxtToFile(fileName: string, textData: string) {
const blobData = new Blob([textData], { type: 'text/plain' });
const urlToBlob = window.URL.createObjectURL(blobData);


const a = document.createElement('a');
a.style.setProperty('display', 'none');
document.body.appendChild(a);
a.href = urlToBlob;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(urlToBlob);
a.remove();
}


saveTxtToFile('myFile.json', JSON.stringify(myJson));