Angular 7 - использование FileSaver.js для загрузки файла Excel не работает - PullRequest
0 голосов
/ 03 марта 2019

Я отправляю почтовый запрос на свой сервер для получения файла Excel.В почтальоне я вижу, что мой сервер отправляет Excel, но в Angular я не могу загрузить его, используя библиотеку FileSaver.Js.Есть идеи?

Вот моя html-разметка:

<button (click)="excel()">Export Excel</button> 

Вот мой класс обслуживания:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import * as FileSaver from 'file-saver';
import 'rxjs';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
    constructor(private data: DataService , private formBuilder: FormBuilder ) { }

    ngOnInit()  {
    }

    excel() {
        this.data.excel().toPromise()
            .then(response => this.saveToFileSystem(response));
    }

    private saveToFileSystem(response) {
        const contentDispositionHeader: string = response.headers.get('Content-Disposition');
        const parts: string[] = contentDispositionHeader.split(';');
        const filename = parts[1].split('=')[1];
        const blob = new Blob([response._body], { type: 'text/plain' });

        FileSaver.saveAs(blob, filename);
    }
}

А вот мой метод класса данных для запроса к бэкэнду:

excel() {
    const headers = new HttpHeaders();
    console.log("sentin")
    headers.set('Content-Type', 'application/json; charset=utf-8');
    return this.http.post(this.baseUrl + '/Excel', { headers: headers })
}

1 Ответ

0 голосов
/ 03 марта 2019

Наконец ответ:

Я должен был внести следующие изменения:

  1. Изменить метод saveFileSystem на:

    private saveToFileSystem(response) {
        const blob = new Blob([JSON.stringify(response.body)], { type: 'application/vnd.ms-excel;charset=utf-8' });
        FileSaver.saveAs(blob, "Report.xls");
    }
    
  2. Добавить тип ответа в мой HttpPost, например:

    { responseType: 'text' }
    
...