【问题标题】:Unhandled Exception: FileSystemException: Cannot open file, path ... (OS Error: No such file or directory, errno = 2)未处理的异常:FileSystemException:无法打开文件,路径...(操作系统错误:没有这样的文件或目录,errno = 2)
【发布时间】:2022-12-16 01:51:07
【问题描述】:

我正在尝试使用 dio.download 下载 *.xlsx 文件,但它抛出了错误: 未处理的异常:FileSystemException:无法打开文件,路径 = '/storage/emulated/0/Android/data/com.example.foodagator_app/files/file.xlsx'(操作系统错误:没有这样的文件或目录,errno = 2)

try/catch 块中的另一个错误: FileSystemException:创建失败,路径 = '文件:''(操作系统错误:只读文件系统,errno = 30)

我在androidmanifest中写了外部存储的权限,也尝试了临时目录,但它不起作用。谁能帮我这个?这是我的代码

void download() async {
    var tempDir = await getExternalStorageDirectory();
    File file = File(tempDir!.path + '/file.xlsx');
    try {
      Response response = await dio.download(
        url,
        file,
        options: Options(
          responseType: ResponseType.bytes,
          followRedirects: false,
        ),
      );

      var raf = file.openSync(mode: FileMode.write);
      // response.data is List<int> type
      raf.writeFromSync(response.data);
      await raf.close();
    } catch (e) {
      print('Error is: $e');
    }
  }

  void readFile() async {
    var tempDir = await getExternalStorageDirectory();

    var filePath = tempDir!.path + "/file.xlsx";
    var bytes = File(filePath).readAsBytesSync();
    var decoder = SpreadsheetDecoder.decodeBytes(bytes, update: true);
    for (var table in decoder.tables.keys) {
      print(table);
      print(decoder.tables[table]!.maxCols);
      print(decoder.tables[table]!.maxRows);
      for (var row in decoder.tables[table]!.rows) {
        print('$row');
      }
    }
  }

【问题讨论】:

    标签: flutter download dio


    【解决方案1】:

    出现此错误是因为没有名为文件.xlsx你可以检查文件是否存在

    if(file.existsSync())
    

    如果文件不存在,您可以使用创建一个,

    new File('$path/file.xlsx').create(recursive: true);
    

    【讨论】:

      【解决方案2】:

      在没有tools:ignore="ScopedStorage" 的情况下,在 android 11 及更高版本中使用

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

      【讨论】:

        【解决方案3】:

        在我的例子中,这是因为我将一个 dart 文件移动到另一个文件夹,但我的其他文件仍在使用旧路径引用该文件,您可以使用新路径再次导入文件并使用“package:”关键字来解决这个错误。

        道德:不要使用相对路径将文件导入项目中的任何位置,始终使用“package:”方案。

        【讨论】:

          【解决方案4】:

          您也可以自定义名称。

          String createDownloadDocName(){
              return'${fileName}-${DateTime.now().microsecond}';
            }
          

          【讨论】:

            【解决方案5】:

            抱歉,我在使用 await 时遇到问题 - 我试图在下载文件之前访问它

            【讨论】:

            • 正如目前所写,您的答案尚不清楚。请edit 添加更多详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写出好的答案的信息in the help center
            猜你喜欢
            • 1970-01-01
            • 2020-02-15
            • 1970-01-01
            • 2019-06-29
            • 2022-01-16
            • 2018-03-28
            • 2020-08-10
            • 2020-05-13
            • 1970-01-01
            相关资源
            最近更新 更多