How to create and download text/Json File with dynamic content using angular 2+
it does not have to use any package,try this
https://stackblitz.com/edit/httpsstackoverflowcomquestions51806464how-to-create-and-downloa?file=src/app/app.component.ts
@Component({
...
})
export class AppComponent {
private setting = {
element: {
dynamicDownload: null as HTMLElement
}
}
fakeValidateUserData() {
return of({
userDate1: 1,
userData2: 2
});
}
//
dynamicDownloadTxt() {
this.fakeValidateUserData().subscribe((res) => {
this.dyanmicDownloadByHtmlTag({
fileName: 'My Report',
text: JSON.stringify(res)
});
});
}
dynamicDownloadJson() {
this.fakeValidateUserData().subscribe((res) => {
this.dyanmicDownloadByHtmlTag({
fileName: 'My Report.json',
text: JSON.stringify(res)
});
});
}
private dyanmicDownloadByHtmlTag(arg: {
fileName: string,
text: string
}) {
if (!this.setting.element.dynamicDownload) {
this.setting.element.dynamicDownload = document.createElement('a');
}
const element = this.setting.element.dynamicDownload;
const fileType = arg.fileName.indexOf('.json') > -1 ? 'text/json' : 'text/plain';
element.setAttribute('href', `data:${fileType};charset=utf-8,${encodeURIComponent(arg.text)}`);
element.setAttribute('download', arg.fileName);
var event = new MouseEvent("click");
element.dispatchEvent(event);
}
}
<a (click)="dynamicDownloadTxt()" >download Txt</a>
<a (click)="dynamicDownloadJson()" >download JSON</a>
Firstly, there is a library we can use to handle saving the file. I've just tested it with FileSaver which seems to work, so that seems a good place to start.
Secondly, configure your HTTP request to return a Blob. Using HttpClient
, we can simply do:
let url = "https://jsonplaceholder.typicode.com/todos/1";
this.http.get(url, {responseType: 'blob'})
Finally, in the subscribe, save the blob. Using the npm
package I mentioned earlier, this would be done like so:
import { saveAs } from 'file-saver/FileSaver';
// ...
let url = "https://jsonplaceholder.typicode.com/todos/1";
this.http.get(url, {responseType: 'blob'})
.subscribe((res) => {
console.log(res)
saveAs(res, "myfile.json")
})
The second option is the filename.
Here is StackBlitz demo
Just uncomment the saveAs
line if you want to see it download the file.