Jun Kang
Jun Kang

Reputation: 1275

How do I save a blob response type in Angular 4+

So I am calling an API, which returns to my Angular a file, like so:

getFile(fileInformation) {
  const req = new HttpRequest('POST', 'filedownload', fileInformation, { reportProgress: true, responseType: "blob" });
  return this.http.request(req);
}

And in the API Controller (I followed this SO top answer to figure this step out):

Public Function GetFile(fileInformation As FileDto) As HttpResponseMessage
    Dim filePath = Path.Combine(FileConstants.FilePath, fileInformation.FileType, fileInformation.FileName)
    Dim fileStream = New FileStream(filePath, FileMode.Open, FileAccess.Read)

    Dim result = new HttpResponseMessage(HttpStatusCode.OK)
    result.Content = New StreamContent(fileStream)
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream")

    Return result
End Function

The returned result from this call is of HttpResponse, and the body is of type Blob.

HttpResponse: {
  blob: {
    size: 289940,
    type: "application/octet-stream"
  },
  headers: ...,
  status: 200,
  ...
}

How do I now trigger a download for this file in the Angular component where I receive the response?

Upvotes: 2

Views: 22483

Answers (2)

Abolfazl Roshanzamir
Abolfazl Roshanzamir

Reputation: 14852

As @Jason Spradlin pointed out you can use FileSaver package

There is another package to save file :

npm install @progress/kendo-file-saver --save

Usage:

import { saveAs } from '@progress/kendo-file-saver'

saveAs(data: string | Blob, fileName: string, options?: SaveOptions)

1-Data is base64

const result = `data:${YOUR_MIME_TYPE};base64,` + YOUR_DATA;
saveAs(result, YOUR_FILE_NAME);

2-Data is Blob

saveAs(YOUR_DATA, YOUR_FILE_NAME);

Manually:

const file = new window.Blob([data], { type: contentType });

const downloadAncher = document.createElement("a");
downloadAncher.style.display = "none";

const fileURL = URL.createObjectURL(file);
downloadAncher.href = fileURL;
downloadAncher.download = fileName;
downloadAncher.click();

Upvotes: 5

Jason Spradlin
Jason Spradlin

Reputation: 1427

install FileSaver from npm.

npm install --save file-saver

import it into your class where you have the blob instance

import * as FileSaver from 'file-saver';

Then just call

FileSaver.saveAs(blob, fileName);

Upvotes: 23

Related Questions