我正在使用rn-fetch-blob
https://github.com/joltup/rn-fetch-blob,正在创建新文件并将其存储在downloads文件夹中。注意:我正在使用模拟器。现在,当我尝试创建一个新文件并且正在使用download dir时,请参见-> https://github.com/joltup/rn-fetch-blob/wiki/File-System-Access-API#dirs,但是却出现错误,提示权限被拒绝,为什么?如何启用权限,以使文件存储在android react native应用程序的下载文件夹中?
代码:
saveFile = () => {
const fs = RNFetchBlob.fs;
const dirs = RNFetchBlob.fs.dirs;
console.log("directory path: ",dirs.DownloadDir );
const NEW_FILE_PATH = dirs.DownloadDir + '/demo.txt';
console.log("file path: ", NEW_FILE_PATH);
fs.createFile(NEW_FILE_PATH, 'foo', 'utf8');
}
AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission tools:node="remove" android:name="android.permission.READ_PHONE_STATE" />
<uses-permission tools:node="remove" android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission tools:node="remove" android:name="android.permission.READ_EXTERNAL_STORAGE" />
屏幕截图:
答案 0 :(得分:2)
您需要<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
如果您使用的是android 6版本或更高版本,则需要请求运行时权限
答案 1 :(得分:2)
如果android版本高于6,则允许访问rn-fetch-blob中的其他目录,则需要请求运行时权限。链接:https://facebook.github.io/react-native/docs/permissionsandroid
修改后的代码:
import {PermissionsAndroid} from 'react-native';
saveFile = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log("Permission granted");
const fs = RNFetchBlob.fs;
// const base64 = RNFetchBlob.base64;
const dirs = RNFetchBlob.fs.dirs;
console.log(dirs.DownloadDir);
const NEW_FILE_PATH = dirs.DownloadDir + '/test.txt';
fs.createFile(NEW_FILE_PATH, 'foo', 'utf8');
} else {
console.log('Permission denied');
}
} catch (err) {
console.warn(err);
}
}
rn-fetch-blob的其他链接:
1)https://github.com/joltup/rn-fetch-blob/wiki/File-System-Access-API#dirs