有什么方法可以在客户端上创建文本文件并提示用户下载文本文件,而无需与服务器进行任何交互?我知道我不能直接写给他们的机器(安全性和全部),但是我可以创建并提示他们保存吗?
如何在内存中创建文件供用户下载,而不是通过服务器下载?
This below function worked.
private createDownloadableCsvFile(fileName, content) {
let link = document.createElement("a");
link.download = fileName;
link.href = `data:application/octet-stream,${content}`;
return link;
}
We can use the URL api, in particular URL.createObjectURL(), and the Blob api to encode and download pretty much anything.
document.body.innerHTML +=
`<a id="download" download="PATTERN.json" href="${URL.createObjectURL(new Blob([JSON.stringify("HELLO WORLD", null, 2)]))}"> Click me</a>`
download.click()
download.outerHTML = ""
Bonus! Download any cyclic objects, avoid the errors:
TypeError: cyclic object value (Firefox) TypeError: Converting
circular structure to JSON (Chrome and Opera) TypeError: Circular
reference in value argument not supported (Edge)
Using https://github.com/douglascrockford/JSON-js/blob/master/cycle.js
/* JSON.decycle */
if(typeof JSON.decycle!=="function"){JSON.decycle=function decycle(object,replacer){"use strict";var objects=new WeakMap();return(function derez(value,path){var old_path;var nu;if(replacer!==undefined){value=replacer(value)}
if(typeof value==="object"&&value!==null&&!(value instanceof Boolean)&&!(value instanceof Date)&&!(value instanceof Number)&&!(value instanceof RegExp)&&!(value instanceof String)){old_path=objects.get(value);if(old_path!==undefined){return{$ref:old_path}}
objects.set(value,path);if(Array.isArray(value)){nu=[];value.forEach(function(element,i){nu[i]=derez(element,path+"["+i+"]")})}else{nu={};Object.keys(value).forEach(function(name){nu[name]=derez(value[name],path+"["+JSON.stringify(name)+"]")})}
return nu}
return value}(object,"$"))}}
document.body.innerHTML +=
`<a id="download" download="PATTERN.json" href="${URL.createObjectURL(new Blob([JSON.stringify(JSON.decycle(document), null, 2)]))}"></a>`
download.click()
As of April 2014, FileSytem APIs may not be standardized in W3C. Anyone looking at the solution with blob should thread with caution, I guess.
在IE10上有效的解决方案:(我需要一个csv文件,但足以将类型和文件名更改为txt)
var csvContent=data; //here we load our csv data
var blob = new Blob([csvContent],{
type: "text/csv;charset=utf-8;"
});
navigator.msSaveBlob(blob, "filename.csv")
此解决方案直接从tiddlywiki(tiddlywiki.com)github存储库中提取。我在几乎所有浏览器中都使用过tiddlywiki,它的工作原理很像:
function(filename,text){
// Set up the link
var link = document.createElement("a");
link.setAttribute("target","_blank");
if(Blob !== undefined) {
var blob = new Blob([text], {type: "text/plain"});
link.setAttribute("href", URL.createObjectURL(blob));
} else {
link.setAttribute("href","data:text/plain," + encodeURIComponent(text));
}
link.setAttribute("download",filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
Github仓库: 下载保护程序模块
我很高兴使用FileSaver.js。它的兼容性非常好(IE10 +和其他所有功能),并且使用非常简单:
var blob = new Blob(["some text"], {
type: "text/plain;charset=utf-8;",
});
saveAs(blob, "thing.txt");
以下方法适用于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,可用于创建和下载文件。
您可以使用数据URI。浏览器支持各不相同;参见维基百科。例:
<a href="data:application/octet-stream;charset=utf-16le;base64,//5mAG8AbwAgAGIAYQByAAoA">text file</a>
八位字节流将强制进行下载提示。否则,它可能会在浏览器中打开。
对于CSV,您可以使用:
<a href="data:application/octet-stream,field1%2Cfield2%0Afoo%2Cbar%0Agoo%2Cgai%0A">CSV Octet</a>
尝试jsFiddle演示。
If the file contains text data, a technique I use is to put the text into a textarea element and have the user select it (click in textarea then ctrl-A) then copy followed by a paste to a text editor.