Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and download text/Json File with dynamic content using angular 2+

here i want to know how can i create a text file or json file and download it with dynamic data which is going to be filled with.

below is my

service code

  validateUserData(userId) {
    var headers = new Headers();

    return this.http.get(`${this.baseUrl}/Users?userId=`+userId,{headers: headers}).map(result => {

      return result.json();

    });
  }

component.ts

this.service.validateUserData(userId).subscribe( res => {

       console.log(res);    
       new Angular2Txt(res, 'My Report');
     });

here i want to send the Response to a textFile or json file which i have to create it so that user can able to download how can i do it Angular package

i tried the above package but i able to download only empty file

like image 957
2 Developer Avatar asked Aug 12 '18 06:08

2 Developer


3 Answers

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>
like image 70
Chunbin Li Avatar answered Oct 22 '22 00:10

Chunbin Li


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.

like image 5
user184994 Avatar answered Oct 22 '22 00:10

user184994


You could do it like this:

let res = "Text to save in a text file";
const blob = new Blob([res], { type: 'text/csv' });
const url = window.URL.createObjectURL(blob);
window.open(url);
like image 3
John Gilmer Avatar answered Oct 21 '22 22:10

John Gilmer