1

I have the following service which allows me to download a file using http Get

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { saveAs } from 'file-saver';

@Injectable()
export class FileService {

  blob: Blob;
  url: string;

  constructor(private _http: Http) { }

  uploadFile(file: File, filetype: string) {
    console.log('uploading...');
    const endpoint = 'http://localhost:60994/api/file';
    const formData:  FormData = new FormData();
    formData.append(filetype, file, file.name);
    return this._http.post(endpoint, formData);
  }

  getFile() {
    return this._http.get('http://localhost:60994/api/file')
    .subscribe(data => {
      if (data != null)
      {
        this.blob = new Blob([data._body], { type: 'application/vnd.ms-excel' });
        const file = new File([this.blob], 'report.xlsx', { type: 'application/vnd.ms-excel' });
        console.log(this.blob);
        console.log(file);
        this.url = window.URL.createObjectURL(file);
        window.open(this.url);
      }
    });
  }
}

The file(xlsx,xls) when downloaded is mostly corrupt with no data (The file sent by the server has data, and I've checked it myself). Also, The

console.log(this.blob);

and

console.log(file); 

show file with almost exact file size as the one expected from the server (In chrome's console).

The best guess I've come up is that, I'm going wrong in how I am reconstructing the received file .

  • Look at this question/answer: https://stackoverflow.com/questions/44871600/download-file-sent-in-response-angular2 – Ludwig May 03 '18 at 19:53

2 Answers2

0

Your http GET request most probably wants some options to denote that you're interested in the raw response bytes:

this._http.get(url, {responseType: 'blob'}).subscribe(..)

I'm not sure what current your 'TRIAL_PRICE' argument to the call is, but that's certainly not an argument that the angular5 HTTP Client is expecting:

By calling with responseType set to blob, you'll also get back a Blob object as the Observable payload so you won't need the body conversion logic either.

Chris White
  • 29,949
  • 4
  • 71
  • 93
0

Turns out i was using the wrong import (Http) for HTTP GET.

imported import { HttpClient } from '@angular/common/http'; and changed

 getFile() {
        return this._http.get('http://localhost:60994/api/file',{responseType: 'blob'})
        .subscribe(data => saveAs(data));
      }