mercredi 21 juin 2023

How to use downloadFile using the Capacitor?

I am using ember.js and one of the functionality of my component is to download a file. I'm trying to use the Capacitor to download a file.

Issue: Whenever the code below triggers, I am getting this error message on my xcode -> [error] - {"errorMessage":"Unable to download file","message":"Unable to download file","code":"DOWNLOAD"}. I only receive error when using native apps, it works really well for web app.

/components/component.js

import Component             from '@glimmer/component';
import { action }            from '@ember/object';
import { Plugins, FilesystemDirectory, CapacitorHttp, Diretory } from '@capacitor/core';
import { Filesystem, Directory, Encoding } from '@capacitor/filesystem';
import { Http } from '@capacitor-community/http'

export default class ExportLink extends Component {
  @action
  async onClick() {
    this.isRequesting = true;

    try {
      // Fetch the download url, since a download has no Authentication information
      const urlResponse = await this.store
        .fetch('signed_urls', { type: 'post', body: { request_url: this.requestUrl } });
      const options = {
        url: urlResponse.url,
        filePath: `${this.fileName}.${this.args.extension}`,
        fileDirectory: Directory.Documents,
      };
      const response = await Http.downloadFile(options);
      const blob     = await response.blob;
      const downloadResponse = new Response(blob, {
        status: response.status,
        headers: (new Headers(response.headers))
      })

      if (!downloadResponse.ok) {
        throw downloadResponse.statusText
      }

      // create a new download link. Add the content of the download, so the download prompt is immediatly invoked
      const link             = document.createElement('a');
      const objectUrl        = URL.createObjectURL(blob);

      link.setAttribute('href', objectUrl);
      link.setAttribute('download', `${this.fileName}.${this.args.extension}`);
      link.setAttribute('rel', 'noopener noreferrer');
      link.setAttribute('target', '_blank'); // fallback if a direct download isnt supported

      link.dispatchEvent(new MouseEvent('click'));

      URL.revokeObjectURL(objectUrl);
    }
    catch(e) {
      console.error({e: e});
      this.notifications.add(this.intl.t('general.forms.unknown_error'), { type: 'warning' });
    }
    finally {
      this.isRequesting = false;
    }

    return false;
  }
}

Additional Question: What should be the filePath for the android or Ios? Or my question is irrelevant to the issue?




Aucun commentaire:

Enregistrer un commentaire