How to upload excel file correctly with Angular2

This is my service code that makes a post request with a response to the xls file:

exportInternalOrder(body) {
        let user_token: string = this.sessionService.getToken();
        let headers = new Headers();
        headers.append('responseType', 'arraybuffer');
        headers.append('Authorization', 'Bearer ' + user_token);
        return this.http.post(this.config.exportInternalOrder, body,{
            headers: headers
        }).map(res => new Blob([res._body],{ type: 'application/vnd.ms-excel' }));
    }

      

It is supposed to process the response of the excel file. This is the code that calls it:

let objToSend = this.makeObjToSend(false);
this.reportingService.exportExcel(objToSend)
    .subscribe(
        data => {
            this.exportData(data);
        },
        error => {
            this.errorFilterMsg.push({ severity: 'error', detail: 'Report exporting has failed!' });
        }
);

      

And this is saving the file (for some reason window.open does nothing):

exportData(data){       
        let blob = data;
        let a = document.createElement("a");
        a.href = URL.createObjectURL(blob);
        a.download = 'fileName.xls';
        document.body.appendChild(a);
        a.click();        
    }

      

But the file is still saved as damaged. When using postman and curls, it fits. Any help would be appreciated.

+3


source to share


2 answers


responseType

should not be set to headers

, this is the part of the object RequestOptionsArgs

that is passed as the second argument to the function post

, but RequestOptionsArgs

contains headers

, responseType

and others, you can read about it here . So your code should look like this:



import { ResponseContentType } from '@angular/http';

exportInternalOrder(body) {
    let user_token: string = this.sessionService.getToken();
    let headers = new Headers();
    headers.append('Authorization', 'Bearer ' + user_token);
    return this.http.post(this.config.exportInternalOrder, body,{
        headers: headers,
        responseType: ResponseContentType.Blob
    }).map(res => new Blob([res._body],{ type: 'application/vnd.ms-excel' }));
}

      

+8


source


I am writing this ... it will be helpful for anyone looking for an Angular 2 file upload solution. Below code snippet works for me.



import { ResponseContentType } from '@angular/http';

exportInternalOrder(body) {
    let user_token: string = this.sessionService.getToken();
    let headers = new Headers();
    headers.append('Authorization', 'Bearer ' + user_token);
    return this.http.post(this.config.exportInternalOrder, body,{
        headers: headers,
        responseType: ResponseContentType.Blob}).map(res => new Blob([res.blob()],{ type: 'application/vnd.ms-excel' }));
}

      

+1


source







All Articles