Reputation: 1052
I am working on an Angular 6 project. One of the web service return the octet-stream
of a file. I have to create a Blob
of the file and download it. I am not getting the response inside subscribe
. How can I request for non-json octet-stream
response?
downloadFile(filePath: string): Observable<HttpResponse<Any>> {
this.http.post<any>(this.getFileDownloadPath(), { stringParam: filePath }, { observe: 'response' }).subscribe(
(resp) => {
this.triggerDownloadFile(resp.body);
},
(err) => {
console.log('err');
}
);
}
triggerDownloadFile(data: Response) {
const blob = new Blob([data], { type: 'application/octet-stream' });
const url = window.URL.createObjectURL(blob);
window.URL.revokeObjectURL(url);
window.open(url);
}
Upvotes: 4
Views: 5316
Reputation: 416
import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
name = 'Angular 5';
fileUrl;
constructor(private sanitizer: DomSanitizer) { }
ngOnInit() {
const data = 'some text';
const blob = new Blob([data], { type: 'application/octet-stream' });
this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));
}
}
<a [href]="fileUrl" download="file.txt">DownloadFile</a>
Upvotes: 1