Home > database >  How do I download PDF files with CapacitorHttp
How do I download PDF files with CapacitorHttp

Time:12-01

Do to issues with the server setting being controlled by another party who will not add (CORS) I am forced to use CapacitorHttp to access the file Url.

Here is what I have so far

ts

async downloadPDF( FullName: any, URL: any) {
    const options = {
      url: URL,
      headers: {
        'x-authorization-token': 'XXXXXXXXX',
        'access-control-allow-origin': 'https://XXXXXXXXXXXX/',
        'access-control-allow-methods': 'GET,POST,OPTIONS',
        'access-control-allow-headers': 'Content-Type, X-Authorization-Token, Origin',
      },
      params: { }, // can I add a version of responseType: 'blob' here
    };

  const response: HttpResponse = await CapacitorHttp.get(options);
  // Type 'HttpResponse' is missing the following properties from type 'Blob': size, type, arrayBuffer, slice, and 2 more.ts(2740)

  write_blob({
    directory: Directory.Documents,
    path: `${FILE_DIR}/${FullName}`,
    blob: response
  });
}

and the response is

response {"headers":{
  "Cache-Control":"no-cache,private",
  "Server":"nginx",
  "Etag":"\"632cc89b-1abb7\"","Last-Modified":"Thu,22 Sep 2022 20:42:03 GMT",
  "Content-Disposition":"inline; filename=\"sample upload.pdf\"",
  "Accept-Ranges":"bytes",
  "Content-Length":"109495",
  "Date":"Thu, 24 Nov 2022 16:15:26 GMT",
  "Content-Type":"application/pdf"},
  "url":"https://XXXXXXXXXX",
  "status":200
}

Is there a way I can add a version responseType: 'blob' to CapacitorHttp

CodePudding user response:

Turns out CapacitorHttp causes a lot of issues and for myself it even interfered with @angular/common/http and caused it not to work. I instead used

https://github.com/capacitor-community/http

import { Http, HttpDownloadFileResult } from '@capacitor-community/http';
import { Filesystem, Directory } from '@capacitor/filesystem';

async downloadFile(name: any, URL: any) {
  const options = { url: URL, filePath: `${FILE_DIR}/${name}`, fileDirectory: Directory.Documents, method: 'GET', };
  const response: HttpDownloadFileResult = await Http.downloadFile(options);
}

This downloaded and saved files on iOS and Android with no CORS issues

  • Related