使用纯 javascript 创建下载提示

Ran*_*rma 2 javascript

var a = 'Hello World From Javascript';在当前窗口的 javascript 变量中有一些文本数据(比如)。我想通过javascript执行以下操作-

1. open a new window and write the text data to the window.
2. set the content type to text/plain.
3. set the content-disposition to attachment, so that download prompt comes.
4. user downloads the text data as a text file and saves it to his local disk.
Run Code Online (Sandbox Code Playgroud)

这一切都可以通过javascript实现吗?

我知道我们可以对服务器进行 ajax 调用或重定向,但在这种情况下,而不是遵循上述步骤。但在这种情况下,这些变通办法是不适用的。

小智 5

你可以使用 JS 和 HTML5 特性来做到这一点。请在下面找到示例代码。

        var fileParts = ['Hello World From Javascript'];

        // Create a blob object.
        var bb = new Blob(fileParts,{type : 'text/plain'});

        // Create a blob url for this. 
        var dnlnk = window.URL.createObjectURL(bb);

        var currentLnk = $('#blobFl').attr('href');

        // blobFl is the id of the anchor tag through which the download will be triggered.

        $('#blobFl').attr('href',dnlnk);
        $('#blobFl').attr('download','helloworld.txt');

        // For some reason trigger from jquery dint work for me.
        document.getElementById('blobFl').click();
Run Code Online (Sandbox Code Playgroud)