【问题标题】:How to solve "OS Error: File exists, errno = 17" in flutter?如何解决“操作系统错误:文件存在,errno = 17”?
【发布时间】:2024-01-03 12:22:01
【问题描述】:

我正在尝试下载文件并将其保存在 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。 有什么想法吗?

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

【问题讨论】:

    标签: flutter download


    【解决方案1】:

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

    我的解决方案:将随机字符串附加到文件名。我知道它不是那么优雅,但它确实有效。

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

    【讨论】:

    • 成功了,但是您知道有关此错误的更多信息吗?例如,它的原因是什么。
    • 我不确定,第二次尝试保存同名文件时会出现错误(第一次没有收到错误),即使删除文件。我的理论是存在某种缓存或导致问题的东西。
    • 是的,就是这样。很奇怪。无论如何,谢谢。
    • 这个答案在我的情况下没有提供解决方案。我正在检查文件是否存在,然后我使用open_file 插件打开文件。在我的情况下 File.exist(file) 返回 false 但 dio.download 显示同样的错误:OS Error: File exists, errno = 17
    • 我也在检查Dio().head(fileUrl) 的文件大小,并用本地文件检查这个值。如果不知何故下载在中间停止并且文件没有自动删除,上述情况将删除损坏的文件并再次下载。因为我得到File.exist(file) 为假,我无法比较大小,我必须下载文件。如前所述引发错误OS Error: File exists, Errno = 17
    最近更新 更多