Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 download file with post request

I have a button defined as:

<button pButton type="button" label="Download" data-icon="fa-cloud-download" (click)="download()"></button>

where the download method delegates to a service, and the service call the api with a post method:

download(model:GlobalModel) {
        let downloadURL = base + "rest/process/download";
        let body = JSON.stringify(model);
        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});   

        this.http.post('http://localhost:48080/rest/process/download', body, options)
            .toPromise()
            .then(
                response => {
                    console.log(response);       
                    var mediaType = 'application/zip';
                    var blob = new Blob([response.blob()], {type: mediaType});
                    var filename = 'project.zip';
                    saveAs(blob, filename);//FileSaver.js libray
                });

    }

But by now the blob() method has not been implemented and there are other answers using _body but there is an typescript error like "_body is private".

The browser displays the download window, but when I download the file is corrupted and cannot open it (I check with postman and the file is generated OK from the server).

How could I download a file properly?... if not possible, There is available a workaround?

like image 740
Sergio Avatar asked Jul 03 '16 03:07

Sergio


2 Answers

here is a working lite example https://stackoverflow.com/a/42992377/3752172

Modify controller to POST:

[HttpPost("realisationsFilterExcel")]
public FileResult exportExcell([FromBody] FilterRealisation filter)
{
    var contentType = "application/octet-stream";
    HttpContext.Response.ContentType = contentType;

    PaginationSet<RealisationReportViewModel> itemsPage = _realisationRepository.GetRealisationReportFilter(filter, User);

    RealisationsReportExcell reportExcell = new RealisationsReportExcell();
    var filedata = reportExcell.GetReport(itemsPage);   
    FileContentResult result = new FileContentResult(filedata, contentType)
    {
        FileDownloadName = "report.xlsx"
    };
    return result;
}

Require FileSaver as dep:

npm install file-saver --save 
npm install @types/file-saver --save

Modify method DownloadComponent angular2 to POST

@Input() filter: any;

public downloadFilePost() {
        this.http.post(this.api, this.filter, { responseType: ResponseContentType.Blob })
        .subscribe(
        (response: any) => {
            let blob = response.blob();
            let filename = 'report.xlsx';
            FileSaver.saveAs(blob, filename);
        });
    }

Using

<download-btn [filter]="myFilter" api="api/realisations/realisationsFilterExcel"></download-btn>
like image 178
dev-siberia Avatar answered Nov 13 '22 13:11

dev-siberia


I finally solved using the trick explained in the answer: https://stackoverflow.com/a/37051365/2011421

Here I describe here my particular approach just in case:

download(model:GlobalModel) {
    // Xhr creates new context so we need to create reference to this
    let self = this;
    var pending:boolean = true;

    // Create the Xhr request object
    let xhr = new XMLHttpRequest();

    let url = BASE + "/download";
    xhr.open('POST', url, true);
    xhr.setRequestHeader("Content-type", "application/json");
    xhr.responseType = 'blob';

    // Xhr callback when we get a result back
    // We are not using arrow function because we need the 'this' context
    xhr.onreadystatechange = function () {

        // We use setTimeout to trigger change detection in Zones
        setTimeout(() => {
            pending = false;
        }, 0);

        // If we get an HTTP status OK (200), save the file using fileSaver
        if (xhr.readyState === 4 && xhr.status === 200) {
            var blob = new Blob([this.response], {type: 'application/zip'});
            saveAs(blob, 'project.zip');
        }
    };

    // Start the Ajax request
    xhr.send(JSON.stringify(model));
}

Unfortunately angular2 http object by now is not complete and this solution although useful feels hacky.

like image 35
Sergio Avatar answered Nov 13 '22 12:11

Sergio