【问题标题】:Cannot get the download link after uploading files to firebase storage Flutter将文件上传到firebase存储Flutter后无法获取下载链接
【发布时间】:2022-08-13 22:06:19
【问题描述】:

所以这是我的文件选择和文件上传代码

class Storage with ChangeNotifier {
  PlatformFile? pickedFile;
  UploadTask? uploadTask;

  Future uploadFile() async {
    final path = \'files/${pickedFile!.name}.png\';
    final file = File(pickedFile!.path!);

    final ref = FirebaseStorage.instance.ref().child(path);
    ref.putFile(file);

    

    try {
      final snapshot = await uploadTask!.whenComplete(() {});
      final urlDownload = await snapshot.ref.getDownloadURL();
      print(urlDownload);
    } catch (e) {
      print(\"this is the error $e \" );
    }
  }

  void pickFile() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles();

    if (result != null) {
      File file = File(result.files.single.path!);
      pickedFile = result.files.first;
    } else {
      print(\"no image picked\");
    }}}

该代码适用于上传图像,但之后我没有得到任何下载链接,错误是“用于空值的空检查运算符”我不知道如何修复它,我还是这个主题的新手,请帮助

    标签: flutter firebase firebase-storage


    【解决方案1】:

    我得到了答案,需要将uploadFile方法更改为此

    Future uploadFile() async {
    final path = 'files/${pickedFile!.name}.png';
    final file = File(pickedFile!.path!);
    
    FirebaseStorage storage = FirebaseStorage.instance;
    Reference ref = storage.ref().child(path);
    UploadTask uploadTask = ref.putFile(file);
    uploadTask.then((res) {
      res.ref.getDownloadURL();
    });
    
    
    
    try {
      final snapshot = await uploadTask.whenComplete(() {});
      final urlDownload = await snapshot.ref.getDownloadURL();
      print(urlDownload);
    } catch (e) {
      print("this is the error $e " );
    }
    

    }

    【讨论】:

      猜你喜欢
      • 2021-09-19
      • 2019-06-08
      • 2020-10-20
      • 1970-01-01
      • 2018-01-24
      • 2017-12-03
      • 2018-12-28
      • 2019-11-06
      • 2020-11-20
      相关资源
      最近更新 更多