Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion: document how to write binary files with Filesystem plugin #2113

Open
alextreppass opened this issue May 24, 2024 · 0 comments
Open
Labels
platform: web type: feature request A new feature, enhancement, or improvement

Comments

@alextreppass
Copy link

alextreppass commented May 24, 2024

Feature Request

Plugin

Filesystem

Description

The filesystem example code uses UTF-8 (i.e. a text encoding)

The use-case I have is:

  • Fetching a PDF on the web side from a bucket
  • Writing it to the phone's cache folder with the Filesystem API
  • So that I can then invoke the Share plugin with the file URI

I was really scratching my head for a while trying to download + read a PDF file on the web side via a FileReader, and having to coerce this into a string. I initially followed the docs and used UTF-8, which was creating an invalid PDF as PDFs are binary files.

Platform(s)

Native (not web)

Preferred Solution

Document some example code for writing binary files, not only text files. Something like this might help:

// reads a file as base64
 async readFile(file: File): Promise<string> {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onloadend = () => {
        if (reader.result == null) {
          reject('No result from file reader');
        }
        if (reader.result instanceof ArrayBuffer) {
         reject('Unexpected ArrayBuffer');
        }
        resolve(reader.result);
      };
      reader.onerror = reject;
      reader.readAsDataURL(file);
    });
  }

// downloads a pdf file
const response = await fetch('https://example.com/a.pdf');
const blob = await response.blob();
const file = new File([blob], 'a.pdf' {
  type: blob.type,
});

// stores it to disk
const data = await readFile(file);
const res = await Filesystem.writeFile({
  data: readRes.data,
  directory: Directory.Cache,
  path: file.name,
  // note: no `encoding` param, so that it will write i.e. application/pdf binary data from the base64 stream, not text
});

Alternatives

Additional Context

Thanks!

@ionitron-bot ionitron-bot bot added the triage label May 24, 2024
@ionitron-bot ionitron-bot bot removed the triage label May 24, 2024
@alexgerardojacinto alexgerardojacinto added the type: feature request A new feature, enhancement, or improvement label Jun 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
platform: web type: feature request A new feature, enhancement, or improvement
Projects
None yet
Development

No branches or pull requests

3 participants