有什么方法可以在客户端创建一个文本文件,并提示用户下载它,而不与服务器进行任何交互? 我知道我不能直接写到他们的机器上(安全等),但是我可以创建并提示他们保存它吗?
当前回答
我们可以使用URL api,特别是URL. createobjecturl()和Blob api来编码和下载几乎任何东西。
如果你的下载量很小,这很好:
document.body.innerHTML + = <a id="download" download="PATTERN. "json " href = " $ {URL。createObjectURL(新团([JSON。stringify(“HELLO WORLD”,null, 2))))} " > < / >点击我的 download.click () 下载。outerHTML = ""
如果您的下载量很大,那么不使用DOM,更好的方法是使用下载参数创建一个link元素,并触发单击。
注意link元素并没有被添加到文档中,但是点击仍然可以工作!这可以通过这种方式创建数百个Mo的下载,因为DOM没有被修改(否则DOM中的巨大URL可能是制表符冻结的来源)。
Const堆栈= { 一些:“东西”, 阿洛特:“他们的!” } BUTTONDOWNLOAD。Onclick =(函数(){ let j = document.createElement("a") j.download = "stack_"+Date.now()+".json" j.href = URL。createObjectURL(新团([JSON。Stringify (stack, null, 2)]) j.click () }) <按钮id = " BUTTONDOWNLOAD " >下载!< / >按钮
奖金!下载任何循环对象,避免错误:
TypeError:循环对象值(Firefox 循环结构JSON (Chrome和Opera) TypeError:循环 不支持在值参数中引用(Edge)
使用https://github.com/douglascrockford/JSON-js/blob/master/cycle.js
在本例中,下载json格式的文档对象。
/* 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()
其他回答
您可以使用数据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演示。
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);
}
// Start file download.
download("hello.txt","This is the content of my file :)");
原文:https://ourcodeworld.com/articles/read/189/how-to-create-a-file-and-generate-a-download-with-javascript-in-the-browser-without-a-server
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!');
使用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,它是一个类似文件的不可变原始数据对象;它们可以被读取为文本或二进制数据。
下载文件扩展或没有扩展的例子中,我使用的是JSON。您可以添加数据和扩展。你可以使用mac地址。Json在这里,如你所愿。如果你想添加一个扩展名,在那里添加,否则,只写没有扩展名的文件名。
let myJson = JSON.stringify(yourdata);
let element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(myJson));
element.setAttribute('download', 'MAC-Addresses.json');
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
推荐文章
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 如何使用JavaScript重新加载ReCaptcha ?
- jQuery。由于转义了JSON中的单引号,parseJSON抛出“无效JSON”错误
- 在JavaScript关联数组中动态创建键
- ReactJS和公共文件夹中的图像
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?