如何将映像加载到Firebase存储并获取downloadUrl(Flutter / Firebase)

时间:2019-04-03 17:04:45

标签: firebase flutter

我想实现将文件发送到Firebase Storage以及获得指向它的链接。但是由于某种原因,它不起作用...

void _pickFile() async {
  File file = await FilePicker.getFile(type: FileType.ANY);
  StorageReference ref = FirebaseStorage.instance.ref()
  .child("image${Random().nextInt(999)}.jpg");
  var fileUrl = ref.putFile(file).onComplete.then((file) => 
  file.ref.getDownloadURL());
  print(fileUrl);
  _sendMessage(fileUrl: fileUrl.toString());
}

...
prefixIcon: IconButton(
  icon: Icon(Icons.attach_file),
  color: Colors.white,
  onPressed: () => _pickFile()
)

为什么我得到这个而不是链接?

  

I / flutter(16610):“未来”的实例

我需要在字符串中链接!

出什么问题了?

3 个答案:

答案 0 :(得分:0)

就像日志中所说,fileUrl是一个尚未解决的Future。您应该确保可以解决使用字符串Give的问题。

void _pickFile() async {
  File file = await FilePicker.getFile(type: FileType.ANY);
  StorageReference ref = FirebaseStorage.instance.ref()
    .child("image${Random().nextInt(999)}.jpg");
  String fileUrl = await (await ref.putFile(file).onComplete).ref.getDownloadURL();
  print(fileUrl);
  _sendMessage(fileUrl: fileUrl.toString());
}

答案 1 :(得分:0)

您需要为await函数使用Future

void _pickFile() async {
  File file = await FilePicker.getFile(type: FileType.ANY);
  StorageReference ref = FirebaseStorage.instance.ref()
  .child("image${Random().nextInt(999)}.jpg");
  final StorageUploadTask uploadTask = ref.putFile(file);
  StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
  String downloadUrl = await taskSnapshot.ref.getDownloadURL();
  _sendMessage(fileUrl: downloadUrl);
}

在不使用await

的情况下看起来像这样
void _pickFile() async {
  File file = await FilePicker.getFile(type: FileType.ANY);
  StorageReference ref = FirebaseStorage.instance.ref()
  .child("image${Random().nextInt(999)}.jpg");
  ref.putFile(file).onComplete.then((file){
    var fileUrl = file.ref.getDownloadURL());
    _sendMessage(fileUrl: fileUrl.toString());
  });
}

答案 2 :(得分:0)

这是我上传并获取上传的图片网址的解决方案

首先我用图像选择器获取图像

Future getImage() async {
  var image = await ImagePicker.pickImage(source: ImageSource.gallery);

  setState(() {
    _image = image;
      print('Image Path $_image');
  });
}

然后我上传到Firebase

Future uploadPic(BuildContext context) async {

  String fileName = basename(_image.path);
  StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child(fileName);
  StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
  StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;


  final String url = (await taskSnapshot.ref.getDownloadURL());
  print('URL Is $url');

  setState(() {
    print("Profile Picture uploaded");
    print("....................$url");
    Scaffold.of(context).showSnackBar(
        SnackBar(content: Text('Profile Picture Uploaded')));
  });
}

这是我获得当前上传图像的downloadUrl的部分

  final String url = (await taskSnapshot.ref.getDownloadURL());
  print('URL Is $url');