You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用react-native-fs获取SD卡/外置存储的所有文件与文件夹

操作步骤

1. 依赖安装与基础配置

首先安装react-native-fs库:

npm install react-native-fs --save
# 或使用yarn
yarn add react-native-fs

平台配置

安卓端配置(修改android/app/src/main/AndroidManifest.xml,添加存储权限):

<!-- 安卓12及以下版本权限 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="32" />
<!-- 安卓13及以上版本媒体权限 -->
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
<!-- 如需访问全部外置存储内容,添加全量存储权限 -->
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

iOS端配置(修改ios/项目名/Info.plist,如需访问App共享目录添加以下配置):

<key>UIFileSharingEnabled</key>
<true/>
<key>LSSupportsOpeningDocumentsInPlace</key>
<true/>

2. 动态权限申请

读取存储内容前需要先向用户申请权限,示例代码:

import { PermissionsAndroid, Platform } from 'react-native';
import RNFS from 'react-native-fs';

const requestStoragePermission = async () => {
  if (Platform.OS !== 'android') return true;
  if (Platform.Version >= 33) {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.MANAGE_EXTERNAL_STORAGE
    );
    return granted === PermissionsAndroid.RESULTS.GRANTED;
  } else {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE
    );
    return granted === PermissionsAndroid.RESULTS.GRANTED;
  }
};

3. 获取存储根路径

react-native-fs提供了内置常量可以直接获取存储路径:

const getStorageRoot = () => {
  // 优先取可插拔SD卡路径,不存在则取内置外置存储根路径
  return RNFS.ExternalSDCardPath || RNFS.ExternalStorageDirectoryPath;
};

4. 递归遍历目录获取全部文件/文件夹

通过递归读取目录的方式,拿到所有层级的文件和文件夹信息:

const scanAllFiles = async (dirPath) => {
  try {
    const items = await RNFS.readDir(dirPath);
    const result = [];
    for (const item of items) {
      const currentItem = {
        name: item.name,
        path: item.path,
        isDirectory: item.isDirectory(),
        size: item.size,
        modifyTime: item.mtime
      };
      result.push(currentItem);
      // 文件夹递归遍历子内容
      if (currentItem.isDirectory) {
        const childList = await scanAllFiles(currentItem.path);
        result.push(...childList);
      }
    }
    return result;
  } catch (error) {
    console.log('目录读取失败:', error.message);
    return [];
  }
};

5. 列表展示内容

可以直接用React Native原生的FlatList组件渲染遍历得到的文件列表:

import { FlatList, View, Text } from 'react-native';

const FileDisplay = ({ fileList }) => {
  const renderItem = ({ item }) => (
    <View style={{ padding: 12, borderBottomWidth: 1, borderBottomColor: '#f0f0f0' }}>
      <Text style={{ fontWeight: item.isDirectory ? '600' : '400' }}>
        {item.isDirectory ? '📁' : '📄'} {item.name}
      </Text>
      <Text style={{ fontSize: 12, color: '#666', marginTop: 4 }}>
        路径:{item.path} | 大小:{item.size ? `${(item.size / 1024).toFixed(2)}KB` : '无'}
      </Text>
    </View>
  );

  return <FlatList
    data={fileList}
    renderItem={renderItem}
    keyExtractor={item => item.path}
  />
};

注意事项

  • 安卓11及以上版本申请MANAGE_EXTERNAL_STORAGE权限后,上架应用商店需要提供合理的权限使用说明,符合平台政策要求
  • 存储容量较大时递归遍历会消耗一定时间,建议添加加载状态提示,也可改为层级懒加载避免阻塞UI
  • 部分厂商定制系统的SD卡路径存在差异,需做好异常捕获和兼容处理

内容的提问来源于stack exchange,提问作者Sharjeel Baig

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 18:09:02