【发布时间】:2020-06-28 09:03:20
【问题描述】:
我在使用 Flutter Web 并将图像上传到 Firestore 时遇到问题。我很确定问题出在图像选择器上,因为普通(移动)image picker 不适用于网络。正常的图像选择器返回一个文件,但替代的 image_picker_web 返回一个图像,它在上传时被拒绝,因为它需要一个 Future<File>。
image_picker_web 有一个替代方法来返回我使用过的Uint8List,然后通过dart:html 转换为File - 并且上传正常,但图像已损坏且无法查看。
这是我所做的:
按下按钮 - 选择图像为Uint8List > 转换为Image,存储在内存中并在屏幕上显示
onPressed: () async {
//Upload Image as Uint8List
imageBytes = await ImagePickerWeb.getImage(asUint8List: true);
//Convert Uint8List to Image
_image = Image.memory(imageBytes);
//Show new image on screen
setBottomSheetState(() {
image = _image;
});
},
使用dart:html File 将Uint8List 转换为File 并命名为用户UID.png(已上传PNG)
imageFile = html.File(imageBytes, '${user.uid}.png');
使用方法上传文件
import 'dart:async';
import 'package:firebase/firebase.dart' as fb;
import 'package:universal_html/prefer_universal/html.dart' as html;
String url;
Future<String> uploadProfilePhoto(html.File image, {String imageName}) async {
try {
//Upload Profile Photo
fb.StorageReference _storage = fb.storage().ref('profilephotos/$imageName.png');
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;
}
调用方法
location = await uploadProfilePhoto(imageFile, imageName: '${user.uid}');
将包括位置在内的数据添加到 Firebase 数据库
//Pass new user ID through to users Collection to link UserData to this user
await AdminUserData(uid: user.uid).updateAdminUserData(name: userName, email: userEmail, profilephoto: location);
一切正常,只是图像似乎已损坏,它也以几乎两倍的文件大小返回,这显然意味着文件没有像图像一样返回..
【问题讨论】:
-
经过一些修改,您的代码对我有用:stackoverflow.com/questions/63604931/…
标签: firebase flutter google-cloud-firestore flutter-web