繁体   English   中英

如何在 react-native-document-picker 中将 PDF 转换为 base64?

[英]How to convert PDF to base64 in react-native-document-picker?

我想将 react-native-document-picker 的响应转换为 base64 格式。 作为回应,我得到了文件的 Uri,但不幸的是没有 base64。

这是我的代码:

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;
            }
          }
    } ```


你可以使用一个这个库

react-native-image-base64rn-fetch-blob

import RNFetchBlob from 'rn-fetch-blob';

 RNFetchBlob.fs
  .readFile(filePath, 'base64')
  .then((data) => {
    setdata(data);
  })
  .catch((err) => {});
import { Platform, ActionSheetIOS } from 'react-native';
import DocumentPicker from 'react-native-document-picker';
import ImagePicker from 'react-native-image-crop-picker';
import RNFS from 'react-native-fs';

对于文档转换:

  pickDocument = async (resolve: (payload: any) => void, reject: (payload: any) => void) => {
    try {
      const result = await DocumentPicker.pick({
        type: [DocumentPicker.types.images, DocumentPicker.types.pdf]
      });
      const fileType = result[0].type;
      const fileExtension = fileType.substr(fileType.indexOf('/') + 1);
      const realURI = Platform.select({ android: result[0].uri, ios: decodeURI(result[0].uri), })
      const b64 = await RNFS.readFile(realURI, "base64")
      const filename = result[0].name.replace(/\s/g, '')
      resolve({ b64, fileType, fileExtension, filename });
    } catch {
      reject(new Error('Action cancelled!'));
    }
  }

对于图像转换:

  pickImage = (resolve: (payload: any) => void, reject: (payload: any) => void) => {
    ImagePicker.openPicker({
      width: 300,
      height: 400,
      cropping: true,
    }).then(async response => {
      const { path: b64Content, mime: fileType, filename:name } = response;
      const b64 = await RNFS.readFile(b64Content, "base64")
      const fileExtension = String(fileType).substr(String(fileType).indexOf('/') + 1);
      const filename = name.replace(/\s/g, '')
      resolve({ b64, fileType, fileExtension, filename });
    }).catch(({message})=>{
      console.log('ERROR',message)
      reject(new Error('Action cancelled!'));
    });
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM