用 JavaScript 创建文本文件 [英] Create text file in JavaScript

查看:42
本文介绍了用 JavaScript 创建文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 JavaScript 创建一个文本文件,我知道使用 ActiveX 对象是可能的,但它只能在 IE 浏览器上运行良好.

I am trying to create a text file using JavaScript, I know it is possible by using ActiveX object, but it runs well only on IE browsers.

我的要求是使用 JavaScript 为 Safari 浏览器生成文本文件?

My requirement is to generate a text file using JavaScript for a Safari browsers?

有人能帮我解决这个问题吗?

Can anyone help me in this regard?

推荐答案

另一种方法是使用 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.

这篇关于用 JavaScript 创建文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆