Angular (5) httpclient observe and responseType: 'blob'

前端 未结 3 1319
逝去的感伤
逝去的感伤 2020-12-15 03:56

Context: I\'m trying to download a binary file from a backend (that requires some data posted as json-body) and save it with file-saver using the filename specified by the b

3条回答
  •  爱一瞬间的悲伤
    2020-12-15 04:49

    Other answers are right but they are missing the example.

    The main answer first when the responseType is set the return type of the response is changed to Blob. To solve this add observe: 'response' which returns HTTPResponse.

    Example: I stumbled upon this issue and spent 6 hours solving.

    So, here I present an example to get filename from headers and download the file:

    downloadPDF(url: string): Observable {
    return this.http.get(url, { responseType: 'blob', observe: 'response' }).pipe(
      map((result:HttpResponse) => {
        console.log(result);
        saveAs(result, "Quotation.pdf");
        return result;
      }));
    

    Here the http is instance of HttpClient, saveAs() is a method of FileSaver npm package same as the OP.

    There is one more problem you might get only 5 headers(Cache-Control, Pragma, etc) in the result.headers and not your custom header for e.g. x-filename.

    The reason behind this CORS. Basically CORS doesn't allow browsers to access more than handfull of headers (listed in the link above).

    So solve this you would have to change server/API to send Access-Control-Expose-Headers header with the request.

提交回复
热议问题