且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用 JavaScript 创建文本文件

更新时间:2023-01-23 09:57:59

另一种方法是使用 BlobURL.createObjectURL.包括 Safari 6+ 在内的所有最新浏览器都支持它们.

Another way to do it would be to use a Blob and URL.createObjectURL. All recent browsers including Safari 6+ support them.

var textFile = null,
  makeTextFile = function (text) {
    var data = new Blob([text], {type: 'text/plain'});

    // If we are replacing a previously generated file we need to
    // manually revoke the object URL to avoid memory leaks.
    if (textFile !== null) {
      window.URL.revokeObjectURL(textFile);
    }

    textFile = window.URL.createObjectURL(data);

    // returns a URL you can use as a href
    return textFile;
  };

这是一个示例,它使用这种技术从textarea中保存任意文本代码>.

Here's an example that uses this technique to save arbitrary text from a textarea.

关于该示例的另一件事要注意的是,我使用了 download 属性 在下载链接上.不幸的是,Safari 目前不支持它.然而,在浏览器中,点击时会自动下载文件,而不是在浏览器中打开文件.此外,由于我将 download 属性设置为 info.txt,文件将使用该名称下载,而不是由 createObjectURL 生成的随机名称.

Another thing to note about the example is that I used the download attribute on the download link. Unfortunately, Safari does not currently support it. However in browsers that do, the file will automatically be downloaded when clicked instead of opening the file in the browser. Also, since I set the download attribute to info.txt the file will be downloaded with that name instead of the random name generated by createObjectURL.