如何解决颤振中的"OS Error: File exists, errno = 17"?



我试图下载并保存一个文件在Downlaod目录中,但每次我都会收到这个错误:

I/flutter (21400): FileSystemException: Cannot create file, path = '/storage/emulated/0/Download/contratto.jpg' (OS Error: File exists, errno = 17)

但是如果我在我的存储中搜索这个文件,我找不到它,我不明白。

在清单中,我拥有所有权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

我使用ext_storage包来查找路径,但即使使用path_provider,我也会遇到同样的错误。这是我的代码:

static Future download(String url, String fileName, String extension) async {
_checkPermission();
String _localPath = await ExtStorage.getExternalStoragePublicDirectory(
ExtStorage.DIRECTORY_DOWNLOADS);
Dio dio = Dio();
await dio.download(
url,
_localPath + "/" + fileName + "." + extension,
);
}

我使用的是Flutter 2.0.6。有什么想法吗?

编辑:只有当我第一次保存具有特定名称的文件时,下载才有效,如果我删除它并尝试再次下载,我会收到这个错误。我也尝试过重新安装应用程序,但我仍然收到错误

显然安卓删除文件的方式有问题:第一次它工作,但下一次错误比较,即使我手动删除文件。

我的解决方案:在文件名后面附加一个随机字符串。我知道它不那么优雅,但它很管用。

String filePath =
_localPath + "/" + fileName + Uuid().v4() + "." + extension;

我找到了解决方案:自从Android 11,API级别30以来,有了新的存储保护。您需要请求MANAGE_EXTERNAL_STORAGE访问权限。


解决方案

添加到AndroidManifest.xml

<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

并请求管理外部存储的权限(例如使用Permission_handler(

await Permission.manageExternalStorage.request();

使用MANAGE_EXTERNAL_STORAGE可能不是一个好主意。

只有当您的应用程序无法有效使用更隐私友好的API(如存储访问框架或媒体商店API(时,才应请求MANAGE_EXTERNAL_STORAGE权限。此外,应用程序对权限的使用必须属于允许的使用范围,并且必须与应用程序的核心功能直接挂钩。如果您的应用程序包含与以下示例类似的用例,则可能允许它请求MANAGE_EXTERNAL_STORAGE权限:

File managers
Backup and restore apps
Anti-virus apps
Document management apps
On-device file search
Disk and file encryption
Device-to-device data migration

https://developer.android.com/training/data-storage/manage-all-files

相关内容

最新更新