在最新版本的Firebase Storage中,方法.put(...)
似乎已经被弃用,取而代之的是.putData(Uint8List(和.putFile(…(,我还没有为Flutter Web找到解决方案。
我正在尝试的代码是这样的,但它没有返回任何内容或抛出任何错误。
_startFilePicker() async {
InputElement uploadInput = FileUploadInputElement();
uploadInput.click();
uploadInput.onChange.listen((e) {
// read file content as dataURL
final files = uploadInput.files;
if (files.length == 1) {
final file = files[0];
FileReader reader = FileReader();
reader.onLoadEnd.listen((e) async {
setState(() {
uploadedImage = reader.result;
});
await uploadImage();
});
reader.onError.listen((fileEvent) {});
reader.readAsArrayBuffer(file);
}
});
}
Future uploadImage() async {
StorageReference storageReference =
FirebaseStorage.instance.ref().child(userID + '/userPhoto');
try {
StorageUploadTask uploadTask = storageReference.putData(uploadedImage);
await uploadTask.onComplete;
} catch (e) {
print(e);
}
print('File Uploaded');
storageReference.getDownloadURL().then((fileURL) {
setState(() {
_formData['photo'] = fileURL;
updateUserData({'photo': fileURL});
});
});
}
我做错了什么吗?或者有更好的方法吗?
更新-2021年4月14日-使用firebase_core: ^1.0.2
和firebase_storage: ^8.0.3
import 'package:firebase_storage/firebase_storage.dart';
import 'package:path/path.dart';
import 'dart:io';
Future uploadProfilePhotoToFirebase(File _image) async {
String fileName = basename(_image.path); //Get File Name - Or set one
Reference firebaseStorageRef = FirebaseStorage.instance.ref().child('uploads/$fileName');
TaskSnapshot uploadTask = await firebaseStorageRef.putFile(_image);
String url = await uploadTask.ref.getDownloadURL(); //Get URL
return await membersCollection.doc(uid).update({ //Update url in Firestore (if required)
'displayPhoto': url,
});
}
旧答案
尝试使用firebase包-这是在firebase7.3.0上运行的,它是firebase_core 0.5.0 的依赖项
import 'dart:async';
import 'package:firebase/firebase.dart' as fb;
import 'dart:html' as html;
String url;
Future<String> uploadProfilePhoto(html.File image, {String imageName}) async {
try {
//Upload Profile Photo
fb.StorageReference _storage = fb.storage().ref('displayPhotos/$imageName');
fb.UploadTaskSnapshot uploadTaskSnapshot = await _storage.put(image).future;
// Wait until the file is uploaded then store the download url
var imageUri = await uploadTaskSnapshot.ref.getDownloadURL();
url = imageUri.toString();
} catch (e) {
print(e);
}
return url;
}