React Native RN-fetch-blob bad base64 -仅限Android的问题

ukqbszuj  于 2023-11-21  发布在  React
关注(0)|答案(2)|浏览(183)

我在react native中遇到了一个问题,我从API下载了一个base 64字符串,并在移动的设备上将其渲染为PDF。
该项目是用React native构建的-代码在iOS上运行良好,但在Android上我们得到了一个'bad base 64' /无效的PDF格式错误。
代码:

//fetch on button click
 getBill = () => {
    if (Platform.OS === "android") {
      this.getAndroidPermission();
    } else {
      this.downloadBill();
    }
  };

//check user has permissions on device (only for android)
getAndroidPermission = async () => {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
      );
      const grantedRead = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE
      );

      if (
        granted === PermissionsAndroid.RESULTS.GRANTED &&
        grantedRead === PermissionsAndroid.RESULTS.GRANTED
      ) {
        this.downloadBill();
      } else {
        Alert.alert(
          "Permission Denied!",
          "You need to give storage permission to download the file"
        );
      }
    } catch (err) {
      console.warn(err);
    }
  };

//download and display bill
downloadBill = async () => {
    this.setState({ loading: true });
    let billId = this.state.billId;
    let user = await AsyncStorage.getItem("user");
    let parseUser = JSON.parse(user);
    let userToken = parseUser.token;

    RNFetchBlob.config({
      addAndroidDownloads: {
        useDownloadManager: true,
        notification: true,
        path:
          RNFetchBlob.fs.dirs.DownloadDir +
          "/" +
          `billID_${this.state.billId}.pdf`,
        mime: "application/pdf",
        description: "File downloaded by download manager.",
        appendExt: "pdf",
        trusty: true,
      },
    })
      .fetch("GET", `${config.apiUrl}/crm/getbillfile/${billId}`, {
        Authorization: "Bearer " + userToken,
      })
      .then((resp) => {
        let pdfLocation =
          RNFetchBlob.fs.dirs.DocumentDir +
          "/" +
          `billID_${this.state.billId}.pdf`;

        RNFetchBlob.fs.writeFile(pdfLocation, resp.data, "base64");

        FileViewer.open(pdfLocation, {
          onDismiss: () => this.setState({ loading: false }),
        });
      });
  };

字符串
Android manifest:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" /> 
  <intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
    <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
  </intent-filter>


任何帮助将不胜感激

bbmckpt7

bbmckpt71#

你给了错误的文件路径在Android中打开,而在IOS中,它实际上是保存在正确的地方,并从正确的地方打开.
在打开文件之前检查操作系统,然后打开文件。

....
const fpath = `${RNFetchBlob.fs.dirs.DownloadDir}${filename}`;
RNFetchBlob.config({
        addAndroidDownloads: {
            useDownloadManager: true,
            notification: true,
            path: fpath,
            description: "File downloaded by download manager.",
        },
    })
    .fetch("GET", `${config.apiUrl}/crm/getbillfile/${billId}`, {
        Authorization: "Bearer " + userToken,
    })
    .then((resp) => {
        if (OS == "ios") {
            // ... do existing logic    
        } else if (OS === "android") {
            // FileViewer or RNFetchBlob should work.
            RnFetchBlob.android.actionViewIntent(fpath, "application/pdf");
        }
    });
};

字符串

7z5jn7bk

7z5jn7bk2#

终于找到了!
这就是我的回答
从'React'导入React

if (Platform.OS == "android") {

        RNFetchBlob.fs.readFile(uri, 'base64')
            .then((base64Data) => {
                onPostMessage({ type: 'photo', data: `data:image/jpeg;base64,${base64Data}` });
            })
            .catch((error) => console.log(error))
        return;
    }

    RNFetchBlob.fetch('GET', uri)
        .then(response => response.base64())
        .then(base64Data => {
            onPostMessage({ type: 'photo', data: `data:image/jpeg;base64,${base64Data}` });
        })
        .catch(error => {
            console.log(error);
        });

字符串

相关问题