![](/img/trans.png)
[英]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.