Angular 7 - 从服务器下载传入文件

问题描述 投票:0回答:1

我正在向我的后端发送一个帖子请求以接收一个excel文件。我可以在邮递员中看到我的后端正在发送excel,但在角度我无法下载它。有任何想法吗?这是我的HTML代码:

<button (click)="excell()">Export Excell</button> 

这是我的服务类:

export class HomeComponent implements OnInit {



  constructor(private data: DataService , private formBuilder: FormBuilder ) { }

  ngOnInit()  {

    }

    excell(){this.data.excell() 
    console.log("sent")}



}

这是我请求后端的数据类方法:

excell() {
    const headers = new HttpHeaders();
    console.log("sentin")
    headers.set('Content-Type', 'application/json; charset=utf-8');
    return this.http.post(this.baseUrl + '/Excel', { headers: headers })
  }
angular
1个回答
1
投票
textFileDownload() {
    this.httpClient.get('url', {responseType: 'arraybuffer'})
    .subscribe((res) => {
        this.writeContents(res, 'test.txt', 'text/txt'); // file extension
    });
}

writeContents(content, fileName, contentType) {
    const a = document.createElement('a');
    const file = new Blob([content], {type: contentType});
    a.href = URL.createObjectURL(file);
    a.download = fileName;
    a.click();
  }
© www.soinside.com 2019 - 2024. All rights reserved.