将图像从颤动上传到 Firebase 存储

ank*_*mar 1 dart flutter firebase-storage

我想将图像上传到 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.');
            }
    
          });
        }
Run Code Online (Sandbox Code Playgroud)

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

Future UploadImage(BuildContext context) async{

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



// how to proceed?


}
Run Code Online (Sandbox Code Playgroud)

pra*_*996 9

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

String filename = basename(_image.path);

Reference storageReference = FirebaseStorage.instance.ref().child("<Bucket Name>/$filename");
Run Code Online (Sandbox Code Playgroud)

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

final UploadTask uploadTask = storageReference.putFile(file);
Run Code Online (Sandbox Code Playgroud)

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

final TaskSnapshot downloadUrl = (await uploadTask);
Run Code Online (Sandbox Code Playgroud)

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

final String url = await downloadUrl.ref.getDownloadURL();
Run Code Online (Sandbox Code Playgroud)

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

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