1

I'm new in angular and I need to know how to save file from my API on a user computer. In my API, I have DownloadController with downloadChapter method on /download/chapter/{id}. When I call this method from Chrome, my computer just start downloading the chapter file - and it's ok. When I call this method form my DownloadService in angular I get the error in console: ERROR OK.

My download chapter method:

  downloadChapter(id: number): Observable<Blob> {
    return this.http
      .get<Blob>(`${this.basicPath}/chapter/${id}`)
      .pipe(
        tap((res) => {
            console.log(`response: ${res}`);
          },
          (e) => {
            console.log(`error: ${e} - ???`);
          }, () => {
            console.log('win!');
          }),
      );
  }

In API response:

200 OK OK,URL [file:/Users/lukasz/Workspace/Inz/api/booky/uploads/1/6:Solaris%20-%20Maly%20Apokryf.mp3],[Content-Disposition:"attachment;filename=6:Solaris%20-%20Maly%20Apokryf.mp3", Content-Type:"audio/mpeg", Content-Length:"97857000"]

How to fix it? I want to just save the file on a user computer.

2

1 Answer 1

2

Here is an angular 6 example of downloading file from a restful api:

Install file saver: npm install file-saver --save

import { HttpClient } from '@angular/common/http';
import { saveAs } from 'file-saver';

.
.
.
constructor(private http: HttpClient) { }

download() {
    this.http.get('/download/chapter/{id}', {responseType:'blob', observe: 'response'}).subscribe(
      (data : any)=>{
        saveAs(data.body, 'yourfilename.ext');
      },
      (err : HttpErrorResponse)=>{
        console.error('download failed:', err);
      });
}

.
.
.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.