2016-10-10 76 views
0

我在我的网站上有一个表单,它根据输入为用户创建输出。 我想用这个输出创建一个文本文件供用户下载(使用浏览器下载提示符,没有安全问题)。jQuery/Javascript为用户下载创建一个文本文件

有没有办法用Javascript/jQuery做到这一点,而不使用PHP在服务器上首先创建文件?

我可以使用某种Javascript对象作为虚拟文件,以便用户可以下载它(解决用户从服务器下载没有真正的txt文件的问题)吗?

+0

只有JavaScript或JQuery的这是不可能的,我认为。您需要服务器端脚本 – vamsi

+0

对于旧版浏览器(以及简单的纯文本文件),您可以在该文档模式下打开一个窗口。看看这个答案[http://stackoverflow.com/questions/7338640/document-opentext-plain-formatting-ignored-in-webkit-safari-chrome](http://stackoverflow.com/questions/7338640/ document-opentext-plain-formatting-ignored-in-webkit-safari-chrome) –

回答

1

您可以通过使用Blobbrowser support,polyfill)来实现。看看这个example by @UselessCode

(function() { 
 
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); 
 

 
    return textFile; 
 
    }; 
 

 

 
    var create = document.getElementById('create'), 
 
    textbox = document.getElementById('textbox'); 
 

 
    create.addEventListener('click', function() { 
 
    var link = document.getElementById('downloadlink'); 
 
    link.href = makeTextFile(textbox.value); 
 
    link.style.display = 'block'; 
 
    }, false); 
 
})();
<textarea id="textbox">Type something here</textarea> <button id="create">Create file</button> <a download="info.txt" id="downloadlink" style="display: none">Download</a>

+1

我可以添加Blob吗? firefox无法识别它... –

+0

有一个不支持它的浏览器的Blob填充:https://github.com/eligrey/Blob.js –

相关问题