javascript - 使用纯 javascript 创建下载提示

标签 javascript

我在当前窗口的 javascript 变量中有一些文本数据(比如 var a = 'Hello World From 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.

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

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

最佳答案

您可以使用 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();

关于javascript - 使用纯 javascript 创建下载提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13548102/

相关文章:

javascript - 如何在 javascript 中删除数组元素而不使用任何内置数组方法?

javascript - 如何移动/复制文件并在冲突时重命名

javascript - 为什么 fs.readFile 在 Windows 上花费太多时间

javascript 比较两次

javascript - 使用元刷新更新页面的替代方案

javascript - 有标签时最大化表格中的选择宽度

javascript - 使用拦截器延迟所有请求

javascript - 如何在分形绘图递归函数中创建延迟

javascript - 如何使用应用脚本根据单元格值修改谷歌表格图表颜色

javascript - 在网站中点击“赞”应该在 Facebook 中点击“赞”