我在当前窗口的 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/