[英]How to upload image to Firebase Storage and get the DownloadUrl Flutter
[英]How to Load Image to Firebase Storage and get downloadUrl (Flutter/Firebase)
我想實現將文件發送到 Firebase 存儲,以及獲取它的鏈接。 但由於某種原因它不起作用......
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):“未來”的實例
我需要字符串中的鏈接!
問題是什么?
就像日志說的,fileUrl 是一個尚未解析的 Future。 你應該確保它決心使用字符串給出。
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());
}
您需要使用await
for 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());
});
}
這是我上傳和獲取上傳圖片網址的解決方案
首先我用圖像選擇器獲取圖像
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')));
});
}
這是我獲取當前上傳圖像的下載地址的部分
final String url = (await taskSnapshot.ref.getDownloadURL());
print('URL Is $url');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.