最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular 2 download .CSV file click event with authentication - Stack Overflow

programmeradmin0浏览0评论

I'm using a spring boot backend and my api uses a service to send data via an OutputStreamWriter. I can download this in Angular 2 using a click event like so:

Typescript

results(){
window.location.href='myapicall';
}

HTML

<button (click)="results()"
                    class="btn btn-primary">Export</button>

This works just fine; however, I recently implemented security for my api endpoints and now I am receiving a 401 everytime I try to make the call because it's not sending a header.

I wrote a service that I can see the results in the console, but I can't seem to figure out how to download the file.

DownloadFileService

import {Injectable} from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/Rx';

@Injectable()
export class DownloadFileService {

    headers:Headers;
    bearer: string;
    constructor(public http: Http) {}



    getFile(url:string) {
        this.bearer = 'Bearer '+ localStorage.getItem('currentUser');
        this.headers = new Headers();
        this.headers.append('Authorization', this.bearer);

        return this.http.get(url, {headers: this.headers});
    }



}

I tried downloading the data via a blob as suggested in this post: How do I download a file with Angular2

The file that gets downloaded is of type File and the content is:

Response with status: 200 OK for URL:my url

It doesn't actually download the data.

downloadFile(data: any){
        var blob = new Blob([data], { type: 'text/csv' });
        var url= window.URL.createObjectURL(blob);
        window.open(url);
    }



    results(){
        // window.location.href='myapicall';   

         let resultURL =  'myapicall';

        this.downloadfileservice.getFile(resultURL).subscribe(data => this.downloadFile(data)),//console.log(data),
            error => console.log("Error downloading the file."),
            () => console.info("OK");



    }

I'm using a spring boot backend and my api uses a service to send data via an OutputStreamWriter. I can download this in Angular 2 using a click event like so:

Typescript

results(){
window.location.href='myapicall';
}

HTML

<button (click)="results()"
                    class="btn btn-primary">Export</button>

This works just fine; however, I recently implemented security for my api endpoints and now I am receiving a 401 everytime I try to make the call because it's not sending a header.

I wrote a service that I can see the results in the console, but I can't seem to figure out how to download the file.

DownloadFileService

import {Injectable} from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/Rx';

@Injectable()
export class DownloadFileService {

    headers:Headers;
    bearer: string;
    constructor(public http: Http) {}



    getFile(url:string) {
        this.bearer = 'Bearer '+ localStorage.getItem('currentUser');
        this.headers = new Headers();
        this.headers.append('Authorization', this.bearer);

        return this.http.get(url, {headers: this.headers});
    }



}

I tried downloading the data via a blob as suggested in this post: How do I download a file with Angular2

The file that gets downloaded is of type File and the content is:

Response with status: 200 OK for URL:my url

It doesn't actually download the data.

downloadFile(data: any){
        var blob = new Blob([data], { type: 'text/csv' });
        var url= window.URL.createObjectURL(blob);
        window.open(url);
    }



    results(){
        // window.location.href='myapicall';   

         let resultURL =  'myapicall';

        this.downloadfileservice.getFile(resultURL).subscribe(data => this.downloadFile(data)),//console.log(data),
            error => console.log("Error downloading the file."),
            () => console.info("OK");



    }
Share Improve this question edited May 23, 2017 at 12:17 CommunityBot 11 silver badge asked Dec 5, 2016 at 2:06 BhetzieBhetzie 2,93210 gold badges33 silver badges44 bronze badges 1
  • You can go for this, if u want to create csv file stackoverflow.com/questions/20300547/… – Tejashree Commented Oct 12, 2020 at 10:12
Add a comment  | 

2 Answers 2

Reset to default 10

Looks like you just need to parse the body of the response i.e

let parsedResponse = data.text();
this.downloadFile(parsedResponse);

Also I would recommend you use FileSaver to download files as even in 2016 there does not seem to be a standard way to do this across browsers.

let blob = new Blob([data], { type: 'text/csv' });
saveAs(blob, "data.txt");

For a more in depth guide check here

I use FileSaver, too. If you have extension on client side, you can see that it will work properly for CSV files. You just need to add extension manually:

FileSaver.saveAs(res, 'export' + extension);
发布评论

评论列表(0)

  1. 暂无评论