先上代码:支持IE8+,Edge,Firefox,Chrome。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Save Test</title>
<script>
function save(filename,data){
var ua = window.navigator.userAgent.toLowerCase();
//alert(ua);
var version = (ua.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1];
if(ua.indexOf("edge") > -1 || (ua.indexOf("msie") == -1 && version =='11.0') || (ua.indexOf("msie") > -1 && version == '10.0' )) {
window.navigator.msSaveOrOpenBlob(new Blob([ data ]), filename);
return;
}
// for IE9-
if(ua.indexOf("msie") > -1 && (version == '9.0' || version == '8.0')){
var frame = document.createElement("iframe");
if (frame) {
document.body.appendChild(frame);
frame.setAttribute("style", "display:none");
frame.contentWindow.document.open("txt/html", "replace");
frame.contentWindow.document.write(data);
frame.contentWindow.document.close();
frame.focus();
frame.contentWindow.document.execCommand("SaveAs", true,
filename);
document.body.removeChild(frame);
}
}else if(ua.indexOf('firefox')>-1 || ua.indexOf('chrome')>-1){
var blob = new Blob([data]);
var link = document.getElementsByTagName('a')[0];
link.download = filename;
var url = URL.createObjectURL(blob);
link.href = url;
//URL.revokeObjectURL(url);
}
}
window.onload = function(){
var data = 'hello world!';
save('file.txt',data);
}
</script>
</head>
<body>
<a>Save</a>
</body>
</html>
保存文件到本地用到的知识:
1. Blob对象
Blob = Binary Large Object的缩写,直译为二进制大对象
1.1 创建Blob对象
var blob= new Blob(Array,options);
1.2 生成Blob链接
Blob URL是blob协议的URL,它的格式如下:
blob:http://xxx
在绝大部分场景下,我们可以像使用Http协议的URL一样使用Blob URL。常见得场景有: 作为文件得下载地址和作为图片资源地址。
URL.createObjectURL(blob); 如果传入的参数是blob对象的话,则可以生成一个blob链接。
URL.revokeObjectURL() 静态方法用来释放一个之前通过调用 URL.createObjectURL() 创建的已经存在的 URL 对象。当你结束使用某个 URL 对象时,应该通过调用这个方法来让浏览器知道不再需要保持这个文件的引用了。
1.3 msSaveBlob 和 msSaveOrOpenBlob 方法(IE10+)
IE10 以上的版本提供 msSaveBlob 和 msSaveOrOpenBlob 方法允许用户在客户端上保存文件,方法如同从 Internet 下载文件,这是此类文件保存到“下载”文件夹的原因。
msSaveBlob 和 msSaveOrOpenBlob 之间的区别就在于前者仅为用户提供“保存”按钮,而后者不但提供“保存”按钮,还提供“打开”按钮。
2. iframe(IE9-)
iframe 元素会创建包含另外一个文档的内联框架(即行内框架)。
参考:
深入浅出iframe
Web前端之iframe详解