简体   繁体   English

如何使浏览器显示“另存为对话框”,以便用户可以将字符串的内容保存到系统上的文件中?

[英]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:导致这样的事情:

例子

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 html5下载属性
  2. data URI's数据 URI

Found the reference:找到参考:

http://paxcel.net/blog/savedownload-file-using-html5-javascript-the-download-attribute-2/ 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) Internet Explorer(但适用于 Edge v13 及更高版本)
  2. Opera Mini歌剧迷你

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

There is a new spec called the Native File System API that allows you to do this properly like this :有一个名为Native File System API的新规范允许您像这样正确地执行此操作:

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 .这里有一个演示,但我相信它正在使用原始试用版,因此它可能无法在您自己的网站上运行,除非您注册或启用配置标志,而且它显然只能在 Chrome 中运行 If you're making an Electron app this might be an option though.如果你正在制作一个 Electron 应用程序,这可能是一个选择。

There is a javascript library for this, see FileSaver.js on Github有一个 javascript 库,请参阅Github 上的 FileSaver.js

However the saveAs() function won't send pure string to the browser, you need to convert it to blob :但是saveAs()函数不会将纯字符串发送到浏览器,您需要将其转换为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:然后在 blob 上调用saveAs ,如下所示:

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>当然记得使用<script src=FileSaver.js>在您的网页上包含上述 javascript 库

This is possible using this cross browser javascript implementation of the HTML5 saveAs function: https://github.com/koffsyrup/FileSaver.js这可以使用 HTML5 saveAs函数的跨浏览器 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.如果您只想保存文本,那么上述脚本适用于所有浏览器(包括所有版本的 IE),只使用 JS。

Solution using only javascript仅使用 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);

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

Using execComand:使用执行命令:

<input type="button" name="save" value="Save" onclick="javascript:document.execCommand('SaveAs','true','your_file.txt')">

In the next link: execCommand在下一个链接中: execCommand

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 HTTP标头使浏览器显示“另存为”对话框并保存文件 - HTTP headers to make browser show “save as” dialog and save file 使用blob内容作为文件在浏览器中生成“保存文件”对话框 - Generate a Save File dialog in browser using blob content as the file 如何在javascript中向浏览器“保存文件”对话框添加事件 - How to add an event to browser 'save file' dialog in javascript 如何在浏览器的另存为对话框中更改自动填充的文件名? - How to change the automatically populated file name in the browser's Save As dialog? 如何弹出包含星级评分系统的窗口,以便用户输入他的评级 - How can I pop up a window containing a star rating system, so a user can input his rating 如何为脚本提供文件系统,以便将数据保存到磁盘? - How do I provide my script with the file system so I can save data to disk? 强制浏览器在文件下载时打开“另存为”对话框 - Forcing browser to open “Save As” dialog on file download AngularJS:显示操作系统“文件保存”对话框,但实际上不保存 - AngularJS: display an OS “file save” dialog but not actually save 如何另存为 html 文件,嵌入浏览器显示? - How to save-as html file, an embeded browser display? 提示用户使用“另存为”对话框保存文件? - Prompting user to save file using a 'Save-as' dialog?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM