首页 > 解决方案 > 下载管理器下载失败文件未下载到目的地

问题描述

我正在尝试下载来自 api 的图像。我正在使用rn-fetch-blob包下载文件。但这里的问题是当我点击下载文件时确实下载了但它给出了一些错误说

下载管理器下载失败,文件没有下载到目的地

任何帮助都会很棒。

这就是我rn-fetch-blob在代码中实现的方式

  const checkPermission = async (image: string) => {
    if (Platform.OS === 'android') {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
          {
            title: 'Storage Permission Required',
            message: 'This app needs access to your storage to download Photos',
            buttonPositive: 'OK',
          },
        );
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          console.log('Storage Permission Granted.');
          handleDownload(image);
        } else {
          Alert.alert('Storage Permission Not Granted');
        }
      } catch (err) {
        console.warn(err);
      }
    }
  };
  const getExtention = (filename: string) => {
    //To get the file extension
    return /[.]/.exec(filename) ? /[^.]+$/.exec(filename) : undefined;
  };

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const handleDownload = async (image: string) => {
    let date = new Date();
    let image_url = image;

    let ext = getExtention(image_url);
    const {config, fs} = RNFetchBlob;
    let pictureDir = fs.dirs.PictureDir;
    let options = {
      fileCache: true,
      addAndroidDownloads: {
        useDownloadManager: true,
        notification: true,
        path:
          pictureDir +
          '/wallace_' +
          Math.floor(date.getTime() + date.getSeconds() / 2) +
          '.' +
          ext,
        description: 'Image',
      },
    };
    config(options)
      .fetch('GET', image_url)
      .then((res) => {
        console.log(res.path());
        Alert.alert('Image Downloaded Successfully.');
      })
      .catch((err) => {
        Alert.alert('Download Failed', err.message);
      });
  };

return <View>
              <TouchableWithoutFeedback
                onPress={() => handleShare(src.portrait)}>
                <Text variant="buttonText">Share Image</Text>
              </TouchableWithoutFeedback>
            </View>

标签: react-nativedownload-managerrn-fetch-blob

解决方案


推荐阅读