【问题标题】:uploading image to firebase storage from flutter从颤振上传图像到firebase存储
【发布时间】:2021-04-07 00:51:27
【问题描述】:

我想将图像上传到 Firebase 存储,但我注意到大多数在线可用代码(文档除外)已被弃用。 由于我是 Flutter 新手,因此我阅读了图像选择器和 Firestore 的文档。 我能够弄清楚图像选择器,但是在 Firestore 中上传让我很艰难。

下面是 imagepicker 的代码,我成功地做到了:

 File _image;
     final picker = ImagePicker();
    
    Future getImage() async {
          final pickedFile =  await ImagePicker().getImage(source: ImageSource.camera);
          setState(() {
            if (pickedFile != null) {
              _image = File(pickedFile.path);
    
    
            } else {
              print('No image selected.');
            }
    
          });
        }

现在我不知道如何完成上传到 Firebase 存储功能:

Future UploadImage(BuildContext context) async{

String filename = basename(_image.path);
firebase_storage.FirebaseStorage storage = firebase_storage.FirebaseStorage.instance;



// how to proceed?


}

【问题讨论】:

标签: flutter dart firebase-storage


【解决方案1】:

因为你有文件名。我只会为此使用您的代码。

String filename = basename(_image.path);

Reference storageReference = FirebaseStorage.instance.ref().child("<Bucket Name>/$filename");

在获得对存储桶的引用后,您现在需要将文件放入该存储桶中。

final UploadTask uploadTask = storageReference.putFile(file);

现在您需要图片的网址。为此,您需要等待上传完成。

final TaskSnapshot downloadUrl = (await uploadTask);

现在完成此操作后,您可以使用获取文件的 URL

final String url = await downloadUrl.ref.getDownloadURL();

这个答案是针对版本号firebase_storage: ^5.2.0

希望这会有所帮助。如果有任何疑问,请告诉我。

【讨论】:

  • 是的,它成功了,非常感谢。我之前曾将图像上传到 Firestore,但该代码已被贬值。作为初学者,我在阅读文档时遇到了问题。我感谢您解释每个步骤。干杯!!
  • 没问题很乐意提供帮助。
  • @pradyot1996 如果我错误地选择了一个大文件,有没有办法回滚上传?
  • @mohamed stackoverflow.com/a/54175316/8244668 发现此删除文件。自己还没试过。
猜你喜欢
  • 1970-01-01
  • 2021-03-07
  • 2022-01-17
  • 1970-01-01
  • 2021-02-26
  • 2021-04-03
  • 2020-09-26
  • 1970-01-01
  • 2019-10-29
相关资源
最近更新 更多