Как получить ответы blob с помощью Angular 2+ @angular/http module?
Я пытаюсь загрузить PDF файл из приложения angular 2...
этот код работает:
var reportPost = 'variable=lsdkjf';
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost/a2/pdf.php", true);
xhr.responseType = 'blob';
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(xhr.readyState == 4 && xhr.status == 200) {
var blob = new Blob([this.response], {type: 'application/pdf'});
saveAs(blob, "Report.pdf");
}
}
xhr.send(reportPost);
но я бы хотел использовать angular 2 встроенный клиент Http.
небольшое исследование:
и некоторый тестовый код:
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.http.post('http://localhost/a2/pdf.php', reportPost, {
headers: headers
})
.retry(3)
// .map( (res:any) => res.blob() ) // errors out
.subscribe(
(dataReceived:any) => {
var blob = new Blob([dataReceived._body], {type: 'application/pdf'});
saveAs(blob, "Report.pdf");
},
(err:any) => this.logError(err),
() => console.log('Complete')
);
спасибо!
пс. функция saveAs приходит отсюда: https://github.com/eligrey/FileSaver.js
Ответы
Ответ 1
С выпуском Angular2 final мы можем определить, например, службу:
@Injectable()
export class AngularService {
constructor(private http: Http) {
}
download(model: MyModel) { //get file from service
this.http.post("http://localhost/a2/pdf.php", JSON.stringify(model), {
method: RequestMethod.Post,
responseType: ResponseContentType.Blob,
headers: new Headers({'Content-Type', 'application/x-www-form-urlencoded'})
}).subscribe(
(response) => { // download file
var blob = new Blob([response.blob()], {type: 'application/pdf'});
var filename = 'file.pdf';
saveAs(blob, filename);
});
}
Эта служба получит файл, а затем подаст его пользователю.
Пример для zip файла: Как использовать JAX-RS и Angular2 для загрузки zip файла
Ответ 2
С @4.3, @5
и HttpClientModule, я закончил:
this.http.post(`${environment.server}/my/download`,
data,
{responseType: 'blob', observe: 'response'})
.map( res => ({content: res.body,
fileName: res.headers.get('content-filename')}));
Ответ 3
Смотрите здесь: fooobar.com/info/313433/...
return this._http.get('/api/images/' + _id, {responseType: 'blob'}).map(blob => {
var urlCreator = window.URL;
return this._sanitizer.bypassSecurityTrustUrl(urlCreator.createObjectURL(blob));
})