gpt4 book ai didi

javascript - 如何创建文件并将其存储在下载文件夹android中?

转载 作者:行者123 更新时间:2023-11-29 15:34:27 30 4
gpt4 key购买 nike

我正在使用 rn-fetch-blob https://github.com/joltup/rn-fetch-blob我正在创建新文件并将其存储在下载文件夹中。注意:我正在使用模拟器。现在,当我尝试创建一个新文件并使用下载目录时,请参阅此 -> 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" />

截图:

enter image description here

最佳答案

为了允许访问 rn-fetch-blob 中的其他目录,如果 android 版本高于 6,则需要请求运行时权限。链接: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

2) https://github.com/joltup/rn-fetch-blob

关于javascript - 如何创建文件并将其存储在下载文件夹android中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54474416/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com