Ank*_*iya 11 javascript json export download angular
我正在使用角度2.我想提供下载JSON文件的功能.
就像我有res = {bar:foo}的响应那么我想创建json文件,它将包含这个响应,可以在按钮/锚点击下载.
任何帮助将不胜感激.
Ank*_*iya 24
它比预期的要简单.
constructor(private sanitizer: DomSanitizer){}
generateDownloadJsonUri() {
var theJSON = JSON.stringify(this.resJsonResponse);
var uri = this.sanitizer.bypassSecurityTrustUrl("data:text/json;charset=UTF-8," + encodeURIComponent(theJSON));
this.downloadJsonHref = uri;
}
Run Code Online (Sandbox Code Playgroud)
在模板中包括
<a class="btn btn-clear" title="Download JSON" [href]="downloadJsonHref" download="download.json"></a>
Run Code Online (Sandbox Code Playgroud)
纯JavaScript可以胜任。
downloadJson(myJson){
var sJson = JSON.stringify(myJson);
var element = document.createElement('a');
element.setAttribute('href', "data:text/json;charset=UTF-8," + encodeURIComponent(sJson));
element.setAttribute('download', "primer-server-task.json");
element.style.display = 'none';
document.body.appendChild(element);
element.click(); // simulate click
document.body.removeChild(element);
}
Run Code Online (Sandbox Code Playgroud)
当我的 json 如此之大时,我遇到了一些问题,我在 Ankur Akvaliya 的答案中添加了一个 Blob 对象并且它有效!!
generateDownloadJsonUri() {
let theJSON = JSON.stringify(this.resJsonResponse);
let blob = new Blob([theJSON], { type: 'text/json' });
let url= window.URL.createObjectURL(blob);
let uri:SafeUrl = this.sanitizer.bypassSecurityTrustUrl(url);
this.downloadJsonHref = uri;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10725 次 |
| 最近记录: |