Ich muss ein Excel von meinem Backend herunterladen, es gibt eine Datei zurück.
Wenn ich die Anfrage mache, erhalte ich die Fehlermeldung:
TypeError: Sie haben "undefined" angegeben, wo ein Stream erwartet wurde. Sie kann ein Observable, Promise, Array oder Iterable bereitstellen.
Mein Code lautet:
this.http.get(`${environment.apiUrl}/...`)
.subscribe(response => this.downloadFile(response, "application/ms-Excel"));
Ich habe versucht bekommen und eine Karte (...), aber es hat nicht funktioniert.
Details: eckig 5,2
verweise:
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/finally';
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/catch';
Inhaltstyp der Antwort:
Content-Type: application/ms-Excel
Was ist falsch?
Versuchen Sie etwas so:
typ: Anwendung/MS-Excel
/**
* used to get file from server
*/
this.http.get(`${environment.apiUrl}`,{responseType: 'arraybuffer',headers:headers} )
.subscribe(response => this.downLoadFile(response, "application/ms-Excel"));
/**
* Method is use to download file.
* @param data - Array Buffer data
* @param type - type of the document.
*/
downLoadFile(data: any, type: string) {
var blob = new Blob([data], { type: type});
var url = window.URL.createObjectURL(blob);
var pwa = window.open(url);
if (!pwa || pwa.closed || typeof pwa.closed == 'undefined') {
alert( 'Please disable your Pop-up blocker and try again.');
}
}
Blobs werden mit dem Dateityp vom Backend zurückgegeben. Die folgende Funktion akzeptiert alle Dateitypen und Popup-Download-Fenster:
downloadFile(route: string, filename: string = null): void{
const baseUrl = 'http://myserver/index.php/api';
const token = 'my JWT';
const headers = new HttpHeaders().set('authorization','Bearer '+token);
this.http.get(baseUrl + route,{headers, responseType: 'blob' as 'json'}).subscribe(
(response: any) =>{
let dataType = response.type;
let binaryData = [];
binaryData.Push(response);
let downloadLink = document.createElement('a');
downloadLink.href = window.URL.createObjectURL(new Blob(binaryData, {type: dataType}));
if (filename)
downloadLink.setAttribute('download', filename);
document.body.appendChild(downloadLink);
downloadLink.click();
}
)
}
Nachdem ich viel Zeit mit der Suche nach einer Antwort auf diese Antwort verbracht hatte: Wie kann ich ein einfaches Image von meinem in Node.js geschriebenen restful API-Server in eine Angular-Komponenten-App herunterladen, habe ich schließlich eine schöne Antwort in diesem Web gefunden. Angular HttpClient Blob . Im Wesentlichen besteht es aus:
API Node.js restful:
/* After routing the path you want ..*/
public getImage( req: Request, res: Response) {
// Check if file exist...
if (!req.params.file) {
return res.status(httpStatus.badRequest).json({
ok: false,
msg: 'File param not found.'
})
}
const absfile = path.join(STORE_ROOT_DIR,IMAGES_DIR, req.params.file);
if (!fs.existsSync(absfile)) {
return res.status(httpStatus.badRequest).json({
ok: false,
msg: 'File name not found on server.'
})
}
res.sendFile(path.resolve(absfile));
}
Angular 6 getesteter Komponentenservice (EmployeeService in meinem Fall):
downloadPhoto( name: string) : Observable<Blob> {
const url = environment.api_url + '/storer/employee/image/' + name;
return this.http.get(url, { responseType: 'blob' })
.pipe(
takeWhile( () => this.alive),
filter ( image => !!image));
}
Vorlage
<img [src]="" class="custom-photo" #photo>
Komponententeilnehmer und Verwendung:
@ViewChild('photo') image: ElementRef;
public LoadPhoto( name: string) {
this._employeeService.downloadPhoto(name)
.subscribe( image => {
const url= window.URL.createObjectURL(image);
this.image.nativeElement.src= url;
}, error => {
console.log('error downloading: ', error);
})
}
Ich bin hier gelandet, als ich nach "rxjs download file using post" gesucht habe.
Dies war mein Endprodukt. Es verwendet den in der Serverantwort angegebenen Dateinamen und Dateityp.
import { ajax, AjaxResponse } from 'rxjs/ajax';
import { map } from 'rxjs/operators';
downloadPost(url: string, data: any) {
return ajax({
url: url,
method: 'POST',
responseType: 'blob',
body: data,
headers: {
'Content-Type': 'application/json',
'Accept': 'text/plain, */*',
'Cache-Control': 'no-cache',
}
}).pipe(
map(handleDownloadSuccess),
);
}
handleDownloadSuccess(response: AjaxResponse) {
const downloadLink = document.createElement('a');
downloadLink.href = window.URL.createObjectURL(response.response);
const disposition = response.xhr.getResponseHeader('Content-Disposition');
if (disposition) {
const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
const matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
const filename = matches[1].replace(/['"]/g, '');
downloadLink.setAttribute('download', filename);
}
}
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}