【问题标题】:Firebase Storage upload picture from gallery Flutter (No error)Firebase 存储从画廊 Flutter 上传图片(无错误)
【发布时间】:2021-05-08 14:54:16
【问题描述】:

我想将从图库中选择的图片上传到 Firestore 存储,这是我的第一次,但我阅读了文档并在互联网上查看,这就是我写的(它可以正常工作,但在存储上什么也没做) .

下面的代码,我测试了 imgFromGallery 并且它可以工作,可能问题是存储功能。

Future<File> imgFromGallery() async {
  try {
    final ImagePicker _picker = ImagePicker();
    final PickedFile imageFile =
        await _picker.getImage(source: ImageSource.gallery, imageQuality: 50);

    //If there is no image selected, return.
    if (imageFile == null) return null;
    //File created.
    File tmpFile = File(imageFile.path);
    //it gives path to a directory - path_provider package.
    final appDir = await getApplicationDocumentsDirectory();
//filename - returns last part after the separator - path package.
    final fileName = tmpFile.path.split('/').last;
//copy the file to the specified directory and return File instance.
    return tmpFile = await tmpFile.copy('${appDir.path}/$fileName');
  } catch (e) {
    print(e);
    return null;
  }
}

//保存文件到Storage函数

Future<void> setPicture(String pathStorage) async {
    try {
      final File file = await imgFromGallery();
      if (file == null) return;
      FirebaseStorage.instance.ref(pathStorage).putFile(file);
      return;
    } catch (e) {
      print(e);
    }
  }

附: : 我想把上传图片的URL作为“setPicture”的返回,但是我还是不知道怎么做。

【问题讨论】:

    标签: firebase flutter firebase-storage


    【解决方案1】:

    离你只有几步之遥!

    TaskSnapshot task = await FirebaseStorage.instance.ref(pathStorage).putFile(file);
    

    上传成功后会得到TaskSnapshot。那有一个参考成员ref

    String image_url = await task.ref.getDownloadURL();
    

    这个image_url是上传图片的网址。

    参考:What is the the method to use onComplete function to add Images to Firebase Storage

    【讨论】:

    • 很好,谢谢你的朋友,但现在如果我连续调用同一个函数 2 次,我的应用程序就会崩溃。你知道为什么吗?
    • stackoverflow.com/questions/66048537/…这是帖子,我会尝试让它再次崩溃并发布错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 2021-08-18
    • 2016-11-28
    • 2017-09-21
    • 2020-12-30
    相关资源
    最近更新 更多