How to convert PDF to base64 in react-native-document-picker?
Asked Answered
H

3

7

I would like to convert the response of react-native-document-picker to base64 format. As a response I get the Uri of the file but unfortunately no base64.

this is my code:

const openDocumentFile = async () =>{
        try {
            const results = await DocumentPicker.pickMultiple({
              type: [DocumentPicker.types.pdf],
              readContent: true
            });
            for (const res of [results]) {
           
              console.log(res)
          
            };
                
          } catch (err) {
            if (DocumentPicker.isCancel(err)) {
            } else {
              throw err;
            }
          }
    } ```


Haslet answered 4/1, 2021 at 15:42 Comment(0)
R
6

you can use one this libs

react-native-image-base64 or rn-fetch-blob

import RNFetchBlob from 'rn-fetch-blob';

 RNFetchBlob.fs
  .readFile(filePath, 'base64')
  .then((data) => {
    setdata(data);
  })
  .catch((err) => {});
Ralina answered 4/1, 2021 at 16:3 Comment(0)
P
1

You can also use react-native-fs library. It's better to decode the file path/uri.

import RNFS from 'react-native-fs';
...
const base64 = await RNFS.readFile(decodeURIComponent(filePath), 'base64');
...
Pickle answered 6/12, 2023 at 4:21 Comment(0)
S
0
import DocumentPicker from 'react-native-document-picker';
import RNFetchBlob from 'react-native-blob-util';

    const [result, setResult] = React.useState<
        | {
            name: string;
            type: string;
            size: number | null;
            extension: string;
            blob: any;
            path: string;
          }[]
        | undefined
        | null
      >(null);
    
      const handleDocumentUpload = async () => {
        try {
          const res = await DocumentPicker.pickSingle();
          if (!res) {
            throw new Error('File pick cancelled or failed');
          }
          const {
            type: fileType,
            uri: fileUri,
            name: fileName,
            size: fileSize,
          } = res;
    
          if (!fileType || !fileUri || !fileName) {
            throw new Error('Failed to get file information');
          }
          const fileExtension = fileType.substr(fileType.indexOf('/') + 1);
          let realURI = fileUri;
          if (Platform.OS === 'ios') {
            realURI = decodeURI(fileUri);
          }
          const base64Data = await getBase64Data(realURI);
          const sanitizedFileName = fileName.replace(/\s/g, '');
          const path = '/patients';
    
          const newUploadedFile = [
            {
              name: sanitizedFileName,
              type: fileType,
              size: fileSize,
              extension: fileExtension,
              blob: base64Data,
              path: Array.isArray(path) ? path.join() : path,
            },
          ];
          setResult(newUploadedFile);
        } catch (error) {
          console.error('Error picking or processing file:', error);
        }
      };
    
      const getBase64Data = async (uri: string) => {
        try {
          const base64Data = await RNFetchBlob.fs.readFile(uri, 'base64');
          return base64Data;
        } catch (error) {
          console.error('Error reading file as base64:', error);
          throw new Error('Failed to read file');
        }
      };
Satellite answered 22/6, 2024 at 10:37 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.