我正在尝试上传firebase上的图像,使用以下代码:
Future<String> uploadCourseImage(filePath, courseName) async{
File file = File(filePath);
var timestamp = Timestamp.now().millisecondsSinceEpoch;
FirebaseStorage _storage = FirebaseStorage.instance;
try{
await _storage.ref().child('courseImage/${this.TeacherName}/$courseName$timestamp').putFile(file);
}on Exception catch(e){
print(e.hashCode);
}
String downloadURL = await _storage.ref().child('courseImage/${this.TeacherName}/$courseName$timestamp').getDownloadURL();
this.courseURL =downloadURL;
notifyListeners();
return downloadURL;
}
但我得到了这个错误:
未处理的异常:PlatformException(download_error,Object不存在于位置.,null,null(,但我的Object确实存在于位置
我认为使用UploadTask类对象有助于上传文件。
尝试此方法 将图像上传到Firebase Storage,并在上传完成后提取url
Future uploadImage(BuildContext context) async {
FirebaseStorage storage = FirebaseStorage.instance;
String? email = FirebaseAuth.instance.currentUser!.email!;
Reference ref =
storage.ref().child('users/${email + DateTime.now().toString()}/Profile Image: ${DateTime.now().toString()}');
UploadTask uploadTask = ref.putFile(_image!);
final TaskSnapshot downloadUrl = (await uploadTask);
imageUrl = await downloadUrl.ref.getDownloadURL();
}
以下代码对我有效:
//Create a reference to the location you want to upload to in firebase
StorageReference reference =
storage.ref().child('courseImage/${this.TeacherName}/$courseName$timestamp');
//Upload the file to firebase
StorageUploadTask uploadTask = reference.putFile(image);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
// Waits till the file is uploaded then stores the download url
String url = await taskSnapshot.ref.getDownloadURL();