React native:点击按钮使用 rn-fetch-blob 下载 pdf 文件

React native: download pdf file with rn-fetch-blob on click a button

我必须让用户在按下按钮时下载 pdf 文件,我发现我必须使用 rn-fetch-blob 而不是 react-native-fetch-blob。在文档中有这段代码:

const { config, fs } = RNFetchBlob
let DownloadDir = fs.dirs.DownloadDir // this is the Downloads directory.
let options = {
fileCache: true,
addAndroidDownloads : {
useDownloadManager : true, //uses the device's native download manager.
notification : true,
title : "Notification Title", // Title of download notification.
path: DownloadDir + "/me_"+ '.' + extension, // this is the path where your download file will be in
description : 'Downloading file.'
}
}
config(options)
.fetch('GET',"https://whatever_url_u _want/)
.then((res) => {
//console.log("Success");
})
.catch((err) => {console.log('error')}) // To execute when download cancelled and other errors
}

我不知道我能用它做什么!如何在 TouchableOpacity onPress 道具中使用它?请有人可以提供一个详细的例子

PS。我用 POST 方法调用了 API,我收到了一个 link 的 PDF 文件。我觉得

I have to set this link like that
    config(options)
    .fetch('GET',this.state.data.link)
  1. AndroidManifest.xml
  2. 中添加以下权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
  1. 要使用下载管理器,请在 AndroidManifest.xml
  2. 中添加以下操作
<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>
  1. 导入 PermissionsAndroid,来自本机反应的警报(仅 android)
import {PermissionsAndroid, Alert} from "react-native";
  1. 现在在组件中
actualDownload = () => {
   const { dirs } = RNFetchBlob.fs;
  RNFetchBlob.config({
    fileCache: true,
    addAndroidDownloads: {
    useDownloadManager: true,
    notification: true,
    mediaScannable: true,
    title: `test.pdf`,
    path: `${dirs.DownloadDir}/test.pdf`,
    },
  })
    .fetch('GET', 'http://www.africau.edu/images/default/sample.pdf', {})
    .then((res) => {
      console.log('The file saved to ', res.path());
    })
    .catch((e) => {
      console.log(e)
    });
}

downloadFile = () => {
  try {
      const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE);
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        this.actualDownload();
      } else {
        Alert.alert('Permission Denied!', 'You need to give storage permission to download the file');
      }
    } catch (err) {
      console.warn(err);
    } 
}

render(){
  <TouchableOpacity onPress={this.downloadFile}>
    <Text>Download!!!</Text>
  </TouchableOpacity>
}

注意:您需要在运行时请求 android 6 或更高版本的存储权限

最新工作解决方案ios/android

按照 mosabbir tuhin 的回答,然后使用我的函数 actualDownload() 和 permissionFunc() 使 pdf 在 ios还有。

const permissionFunc = async () => {
    if (Platform.OS == 'ios') {
        actualDownload();
    } else {
        if (downloaded) {
            try {
                const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE);
                if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                    actualDownload();
                } else {
                    showSnackbar('You need to give storage permission to download the file');
                }
            } catch (err) {
                console.warn(err);
            }
        }
        else {
            showSnackbar('File is already downloaded.');
        }
    }
}

const actualDownload = () => {
    const { dirs } = RNFetchBlob.fs;
    const dirToSave = Platform.OS == 'ios' ? dirs.DocumentDir : dirs.DownloadDir
    const configfb = {
        fileCache: true,
        useDownloadManager: true,
        notification: true,
        mediaScannable: true,
        title: pdfInfo.pdf,
        path: `${dirToSave}/${pdfInfo.pdf}`,
    }
    const configOptions = Platform.select({
        ios: {
            fileCache: configfb.fileCache,
            title: configfb.title,
            path: configfb.path,
            appendExt: 'pdf',
        },
        android: configfb,
    });

    console.log('The file saved to 23233', configfb, dirs);

    RNFetchBlob.config(configOptions)
        .fetch('GET', `https://aquatherm.s3.ap-south-1.amazonaws.com/pdfs/${pdfInfo.pdf}`, {})
        .then((res) => {
            if (Platform.OS === "ios") {
                RNFetchBlob.fs.writeFile(configfb.path, res.data, 'base64');
                RNFetchBlob.ios.previewDocument(configfb.path);
            }
            setisdownloaded(false)
            if (Platform.OS == 'android') {
                showSnackbar('File downloaded');
            }
            console.log('The file saved to ', res);
        })
        .catch((e) => {
            setisdownloaded(true)
            showSnackbar(e.message);
            console.log('The file saved to ERROR', e.message)
        });
}