React Native文件系统
采用:https://github.com/itinance/react-native-fs#usage-android
# 写入数据
字符串
function writeFile(data: any) { RNFS.writeFile(path, 'Lorem ipsum dolor sit amet', 'utf8') .then((success) => { console.log('FILE WRITTEN!'); }) .catch((err) => { console.log(err.message); }); }
1
2
3
4
5
6
7
8
9二进制数据
function writeFile(data: any) { var base64Data = base64.encode(String.fromCharCode.apply(null, data)) RNFS.writeFile(path, base64Data, "base64") .then((success) => { console.log("FILE WRITTEN" + " " + path); alert("文件已成功写入"); readFile(); }) .catch((err) => { console.log(err.message); }); }
1
2
3
4
5
6
7
8
9
10
11
12
# 读取数据
async function readFile() {
const content = await RNFS.readFile(path, "base64");
console.log("文件内容: " + content);
}
1
2
3
4
2
3
4
# 权限报错
ENOENT: open failed: EACCES (Permission denied), open '/storage/emulated/0/Download/xxx.txt'
# 解决方法
在
AndroidManifest.xml
.... <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> // worked without this also ... <application ... android:requestLegacyExternalStorage="true" // this is needed .... >
1
2
3
4
5
6
7征求许可
在这里,我们使用
react-native-permissions
requestMultiple([PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE, PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE]).then((statuses) => { console.log("BLUETOOTH_SCAN", statuses[PERMISSIONS.ANDROID.BLUETOOTH_SCAN]); console.log("BLUETOOTH_CONNECT", statuses[PERMISSIONS.ANDROID.BLUETOOTH_CONNECT]); // console.log('WRITE_EXTERNAL_STORAGE', statuses[PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE]); // console.log('READ_EXTERNAL_STORAGE', statuses[PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE]); });
1
2
3
4
5
6
上次更新: 2024/08/14, 04:14:33