Flutter Fiebase数据库从Firebase存储获取图像URL

时间:2020-04-03 08:49:49

标签: firebase flutter firebase-realtime-database dart google-cloud-firestore

我想从Firebase中以字符串形式获取图像URL并将其在Cloud Firestore中安全。我可以将图像上传到FirebaseStorage,但是我不能将图像URL作为字符串安全地上传到我的云Firestore。

有人可以帮助我解决这个问题吗?

<!-- language: lang-dart -->

//upload and get image
File imageFile;
  String imageURL;

  Future getImage (bool isCamera) async {
    File image;
    if(isCamera) {
      image = await ImagePicker.pickImage(source: ImageSource.camera);
    }else{
      image = await ImagePicker.pickImage(source: ImageSource.gallery);
    }
    setState(() {
      imageFile = image;
    });
  }

  Future uploadImage(BuildContext context) async {
    String fileName = basename(imageFile.path);
    StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child(fileName);
    StorageUploadTask uploadTask = firebaseStorageRef.putFile(imageFile);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    setState(() {
      imageURL = await taskSnapshot.ref.getDownloadURL();
    });
  }

//upload to realtime Database
RaisedButton(
                  color: Theme.of(context).primaryColor,
                  textColor: Colors.white,
                  child: Text(isEditNote? "Update" : "Save"),
                  onPressed: () async{
                    if(_key.currentState.validate() && imageFile != null){
                      try {
                        if(isEditNote){
                          uploadImage(context);
                          Book book = Book(
                            image: imageURL,
                          );
                          FirestoreService().updateBook(book);
                          Navigator.pop(context);
                        }else {
                          uploadImage(context);
                          Book book = Book(
                            image: imageURL,
                          );
                          await FirestoreService().addBook(book);
                          Navigator.pop(context);}
                      }catch(e){
                        print(e);
                      }
                    }else{

                    }
                  },

1 个答案:

答案 0 :(得分:1)

要获取imageUrl,可以将其设置为

imageUrl = await taskSnapshot.ref.getDownloadURL() ;

定义

getDownloadURL()→将来 异步检索具有可撤销令牌的长期下载URL。可以用于与其他人共享文件,但是如果需要,开发人员可以在Firebase控制台中将其撤消。

在官方文档中:

https://pub.dev/documentation/firebase_storage/latest/firebase_storage/StorageReference-class.html