javascript - RN-fetch-blob 错误 base64 - 仅限 android 问题

标签 javascript android react-native rn-fetch-blob

我在 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 }),
        });
      });
  }; 
安卓 list :
<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>
任何帮助,将不胜感激

最佳答案

您在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");
        }
    });
};

关于javascript - RN-fetch-blob 错误 base64 - 仅限 android 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63725888/

相关文章:

javascript - 日期函数未按预期工作

java - Android/Java 正则表达式匹配加号

android - AsyncTask 与 PHP/MySql 不能正常工作

reactjs - 虚拟化列表 : You have a large list that is slow to update

javascript - 使用 javascript 在元素中创建元素

javascript - 在 js 中使用类与创建独立函数有什么好处

javascript - 我可以有一个没有值的 JavaScript 对象键吗

android - 在 ScrollView 和 ViewFlipper 中启用可滚动的 EditText

react-native - 如何在 React Native 中检测键盘何时打开或关闭

ios - 如何修复不为 iOS 构建的 React Native App