【问题标题】:How to download file from firebase to local phone storage in flutter?如何在flutter中将文件从firebase下载到本地手机存储?
【发布时间】:2021-10-20 10:26:24
【问题描述】:

我是 Flutter 的新手,我对如何实现从 Firebase 下载 PDF 文件的功能一无所知。我浏览了多个关于在 Flutter 应用中将文件从云存储下载到本地存储的教程,但仍然无法正常工作。

当用户按下按钮时我想要

 onPressed: () async {},

然后,它会立即将文件从我的 Firebase 云存储下载到他们的本地文件。

我知道我必须使用writeToFile,但是我该如何实现这个功能呢?

希望你能帮助我,谢谢!

【问题讨论】:

    标签: firebase flutter cloud-storage


    【解决方案1】:

    查看 Firebase Cloud Storage 的文档时,您可以使用以下函数将文件从 Cloud Storage 下载到本地文档文件夹:

    //You'll need the Path provider package to get the local documents folder.
    import 'package:path_provider/path_provider.dart';
    
    Future<void> downloadFileExample() async {
      //First you get the documents folder location on the device...
      Directory appDocDir = await getApplicationDocumentsDirectory();
      //Here you'll specify the file it should be saved as
      File downloadToFile = File('${appDocDir.path}/downloaded-pdf.pdf');
      //Here you'll specify the file it should download from Cloud Storage
      String fileToDownload = 'uploads/uploaded-pdf.pdf';
    
      //Now you can try to download the specified file, and write it to the downloadToFile.
      try {
        await firebase_storage.FirebaseStorage.instance
            .ref(fileToDownload)
            .writeToFile(downloadToFile);
      } on firebase_core.FirebaseException catch (e) {
        // e.g, e.code == 'canceled'
        print('Download error: $e');
      }
    }
    

    您可以在此页面上找到并阅读更多信息:https://firebase.flutter.dev/docs/storage/usage

    要在 onPressed 函数上实现它,我建议将该函数与按钮放在同一个类中,并像这样从 onPressed 执行函数:

    onPressed: () {
      downloadFileExample();
    }
    

    【讨论】:

    • 是的,我阅读了文档,但是如何在我的 onPressed 按钮上实现?
    • 我刚刚编辑过,有一个简短的解释,希望对你有帮助
    猜你喜欢
    • 2020-10-10
    • 2020-08-13
    • 1970-01-01
    • 2019-06-09
    • 2017-02-18
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 2021-07-03
    相关资源
    最近更新 更多