当前位置: 动力学知识库 > 问答 > 编程问答 >

Create text file in JavaScript

问题描述:

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.

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

Can anyone help me in this regard?

网友答案:

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

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

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.

网友答案:

In JavaScript u can use following line to ask user for saving a text file,

window.open("data:text/json;charset=utf-8," + escape("Ur String Object goes here"));

I have tested this in some popular browsers some times back... just ensure that it works in Safari or not.. Good Luck

网友答案:

but my requirement is to generate a text file using javascript for a safari browser

That's not possible with vanilla Javascript due to security restrictions. You can however use server-side javascript such as Node.JS or Ajax or some other server-side technology.

分享给朋友:
您可能感兴趣的文章:
随机阅读: