【问题标题】:Flutter Dio package download pathFlutter Dio 包下载路径
【发布时间】:2018-07-05 16:49:13
【问题描述】:

我的主要目标是从链接下载文件,然后将其保存到手机的内部存储中,以便可以通过手机的文件管理器访问它。我目前正在通过运行包仓库中给出的示例code 来试用Dio 包。运行程序后,我遇到了路径问题。当我使用./example/flutter.png 作为下载路径时,I/flutter (10109): FileSystemException: Cannot open file, path = './example/flutter.png' (OS Error: No such file or directory, errno = 2) 出现了。当我使用(await getApplicationDocumentsDirectory()).path 产生一个String 值:/data/user/0/com.example.downloadexample/app_flutter 作为路径时,没有出现错误,但文件不存在。我尝试了后一种路径的不同变体,但没有成功。有人可以帮我解决这个问题吗?

非常感谢。

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    我用的是http包,不是Dio,代码:

    Future<String> fetchNetFileToDoc(String url, String filename) async {
      final path = await getApplicationDocumentsDirectory();
      File docFile = File('$path/$filename');
        if(await docFile.exists()){
        print( '${docFile.path} exits');
        return docFile.path;
      }
    
      http.Response response = await http.get(url);
      // todo - check status
      await docFile.writeAsBytes(response.bodyBytes, flush: true);
      return docFile.path;
    }
    

    如果我调用此方法,例如:fetchNetFileToDoc('http://a.com/a.mp3', 'a.mp3') 它显示相同的错误:

    FileSystemException: Cannot open file, path= 'Direcotry: '/data/user/0/com.example.master_lu/app_flutter'/a.mp3' (OS Error: No such file or directory, errno = 2)
    

    但如果我使用 getTemporaryDirectory(),请将代码更改为:

    Future<String> fetchNetFileToTemp(String url, String filename) async {
      Directory tempDir = await getTemporaryDirectory();
      String tempPath = tempDir.path;
      File tempFile = File('$tempPath/$filename');
      if(await tempFile.exists()){
        print( '${tempFile.path} exits');
        return tempFile.path;
      }
    
      http.Response response = await http.get(url);
      // todo - check status
      await tempFile.writeAsBytes(response.bodyBytes, flush: true);
      return tempFile.path;
    }
    

    没关系,它适用于内部存储。将文件保存到data/user/0/com.example.master_lu/cache/a.mp3 master_lu 是我的项目的名称。

    最新的=> 我解决了我的问题,await getApplicationDocumentsDirectory 返回Future&lt;Directory&gt;

    所以,这里是正确的代码:

    Future<String> fetchNetFileToDoc(String url, String filename) async {
      final docDir = await getApplicationDocumentsDirectory();
      String docPath = docDir.path;
      File docFile = File('$docPath/$filename');
        if(await docFile.exists()){
        print( '${docFile.path} exits');
        return docFile.path;
      }
    
      http.Response response = await http.get(url);
      // todo - check status
      await docFile.writeAsBytes(response.bodyBytes, flush: true);
      return docFile.path;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-29
      • 2019-12-18
      • 1970-01-01
      • 2020-10-20
      • 2020-10-04
      • 1970-01-01
      • 2021-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多