有什么方法可以在客户端创建一个文本文件,并提示用户下载它,而不与服务器进行任何交互? 我知道我不能直接写到他们的机器上(安全等),但是我可以创建并提示他们保存它吗?
当前回答
HTML5浏览器的简单解决方案…
function download(filename, text) { var element = document.createElement('a'); element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)); element.setAttribute('download', filename); element.style.display = 'none'; document.body.appendChild(element); element.click(); document.body.removeChild(element); } form * { display: block; margin: 10px; } <form onsubmit="download(this['name'].value, this['text'].value)"> <input type="text" name="name" value="test.txt"> <textarea name="text"></textarea> <input type="submit" value="Download"> </form>
使用
download('test.txt', 'Hello world!');
其他回答
以下方法适用于IE11+、Firefox 25+和Chrome 30+浏览器:
<a id="export" class="myButton" download="" href="#">export</a>
<script>
function createDownloadLink(anchorSelector, str, fileName){
if(window.navigator.msSaveOrOpenBlob) {
var fileData = [str];
blobObject = new Blob(fileData);
$(anchorSelector).click(function(){
window.navigator.msSaveOrOpenBlob(blobObject, fileName);
});
} else {
var url = "data:text/plain;charset=utf-8," + encodeURIComponent(str);
$(anchorSelector).attr("download", fileName);
$(anchorSelector).attr("href", url);
}
}
$(function () {
var str = "hi,file";
createDownloadLink("#export",str,"file.txt");
});
</script>
详见行动:http://jsfiddle.net/Kg7eA/
Firefox和Chrome支持数据URI导航,这允许我们通过导航到数据URI来创建文件,而IE出于安全考虑不支持它。
另一方面,IE有用于保存blob的API,可以用来创建和下载文件。
使用Blob:
function download(content, mimeType, filename){
const a = document.createElement('a') // Create "a" element
const blob = new Blob([content], {type: mimeType}) // Create a blob (file-like object)
const url = URL.createObjectURL(blob) // Create an object URL from blob
a.setAttribute('href', url) // Set "a" element link
a.setAttribute('download', filename) // Set download filename
a.click() // Start downloading
}
所有现代浏览器都支持Blob。 Caniuse支持表Blob:
这是一把小提琴
这里是MDN文档
Blob对象表示一个Blob,它是一个类似文件的不可变原始数据对象;它们可以被读取为文本或二进制数据。
根据@Rick的回答,这真的很有帮助。
如果你想以这种方式共享字符串数据,你必须转义字符串数据:
$('a.download').attr('href', 'data:application/csv;charset=utf-8,'+ encodeURI(data));
` 抱歉,我不能评论@Rick的回答,因为我目前在StackOverflow的声誉很低。
分享了一个编辑建议,但被拒绝了。
上面所有的例子在chrome和IE中都运行良好,但在Firefox中却失败了。 请考虑将一个锚附加到主体上,并在点击后将其移除。
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob(['Test,Text'], {type: 'text/csv'}));
a.download = 'test.csv';
// Append anchor to body.
document.body.appendChild(a);
a.click();
// Remove anchor from body
document.body.removeChild(a);
如果你只是想把一个字符串转换成可以下载的,你可以使用jQuery尝试一下。
$('a.download').attr('href', 'data:application/csv;charset=utf-8,' + encodeURI(data));