如何在react-native中获取文件的绝对路径?

时间:2018-09-20 10:32:46

标签: react-native react-native-android

我正在寻找react-native中的文件选择器,该文件选择器返回我选择的文件的绝对路径。我当前正在使用react-native-document-picker,但是它以content://com.android.providers.media.documents/document/......的格式提供了相对路径。当我想压缩视频文件时,react-native-ffmpegreact-native-video-processing之类的库需要文件的绝对路径。

5 个答案:

答案 0 :(得分:4)

我实际上是自己想出来的。您可以通过3种方式获得绝对路径。

最方便的方法:使用react-native-document-picker,选择后会给您一个相对路径,类似content://com.android......。将该相对路径传递到react-native-fetch-blob库的Stat(filepath)函数。该对象将返回绝对路径。用file://附加路径以将其用于进一步的操作。

其他两种方法是使用react-native-image picker和CameraRoll(React Native Library)

我希望这会有所帮助!

答案 1 :(得分:2)

安装react-native-fetch-blob以获取文件的路径。 下面是一个示例。

pickFile = async () => {
try {
  const res = await DocumentPicker.pick({
    type: [DocumentPicker.types.allFiles],
  });

  console.log(res.uri);
  //output: content://com.android.providers.media.documents/document/image%3A4055

  RNFetchBlob.fs
    .stat(res.uri)
    .then((stats) => {
      console.log(stats.path);
 //output: /storage/emulated/0/WhatsApp/Media/WhatsApp Images/IMG-20200831-WA0019.jpg
    })
    .catch((err) => {
      console.log(err);
    });
} catch (err) {
  if (DocumentPicker.isCancel(err)) {
  } else {
    throw err;
  }
}};

答案 2 :(得分:2)

首先,您必须请求 Android 权限,因此请确保先调用此函数:

export const requestReadExternalStorage = () => {
  PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE);
};

在调用此函数并接受权限后,您可以将 uri 传递给此函数:

export const getPath = (uri: string) => {
  if (uri.startsWith('content://')) {
    return RNFetchBlob.fs.stat(uri).then(info => info?.path);
  }
  return uri;
};

然后你只需要调用它并使用真正的uri,就像这样:

// res?.uri is the uri returned from the DocumentPicker.pick() response.
const uri = await getPath(res?.uri);

答案 3 :(得分:1)

您可能会忘记为此请求适当的权限(仅适用于andriod):

export async function requestStoragePermission() {

    if (Platform.OS !== "android") return true

    const pm1 = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE);
    const pm2 = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE);

    if (pm1 && pm2) return true

    const userResponse = await PermissionsAndroid.requestMultiple([
        PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
    ]);

    if (userResponse['android.permission.READ_EXTERNAL_STORAGE'] === 'granted' &&
        userResponse['android.permission.WRITE_EXTERNAL_STORAGE'] === 'granted') {
        return true
    } else {
        return false
    }
}

答案 4 :(得分:0)

尝试一下,也许会对您https://www.npmjs.com/package/react-native-file-share-for-android有帮助 但是它仅支持Android

const uploadDocunment = async finalSubmit => {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
        {
          title: 'Storage Permission',
          message: 'App needs access to memory to download the file ',
        },
      );
      if (granted != PermissionsAndroid.RESULTS.GRANTED) {
        ToastAndroid.showWithGravity(
          'You need to give storage permission to download the file',
          ToastAndroid.SHORT,
          ToastAndroid.BOTTOM,
        );
        return false;
      }
      try {
        DocumentPicker.pick({
          type: [DocumentPicker.types.plainText],
        }).then(res => {
          RNFetchBlob.fs.readFile(res.uri, 'utf8').then(text1 => {
            ToastAndroid.showWithGravity(
              'Docunment is Ready!',
              ToastAndroid.SHORT,
              ToastAndroid.BOTTOM,
            );
          });
        });
      } catch (err) {
        if (DocumentPicker.isCancel(err)) {
          ToastAndroid.showWithGravity(
            'File not Selected',
            ToastAndroid.SHORT,
            ToastAndroid.BOTTOM,
          );
        } else {
          throw err;
        }
      }
    };
    uploadDocunment();
  };