Flutter web - 将图像上传到 firebase 存储

Flutter web - Uploading image to firebase storage

我在 flutter web 上使用 firebase_storage: ^8.0.6 包。我想将图像上传到我使用 FilePicker 包获得的 firebase 存储。 问题是新包使用 putFile() 方法上传文件。但是来自 dart:io 的文件在 flutter web 上不起作用,它也不接受来自 dart:html.

的文件对象

我可以使用 putBlob() 方法将图像作为 Blob 上传,但它不会将其作为图像类型上传,但它的类型是 application/octet-stream。我不想以 blob 形式上传图像文件。

  Future<String> uploadImage(PlatformFile file) async {
    try {

      TaskSnapshot upload = await FirebaseStorage.instance
          .ref(
              'events/${file.name}-${DateTime.now().toIso8601String()}.${file.extension}')
          .putBlob(Blob(file.bytes));

      String url = await upload.ref.getDownloadURL();
      
      return url;
    } catch (e) {
      print('error in uploading image for : ${e.toString()}');
      return ';
    }
  } 

如何解决这个问题?

当您使用 File.fromUri() 构造函数并使用 Uri.dataFromBytes 并传递字节从 PlatformFile 对象获取 Uri 时,您仍然可以使用 .putFile

以下代码包含应消除错误的更改:

    TaskSnapshot upload = await FirebaseStorage.instance
        .ref(
            'events/${file.name}-${DateTime.now().toIso8601String()}.${file.extension}')
        .putFile(File.fromUri(Uri.dataFromBytes(file.bytes.toList())));

您可以使用 putData() 方法发送图像并将其元数据设置为图像。

  Future<String> uploadImage(PlatformFile file) async {
    try {

      TaskSnapshot upload = await FirebaseStorage.instance
          .ref(
              'events/${file.path}-${DateTime.now().toIso8601String()}.${file.extension}')
          .putData(
            file.bytes,
            SettableMetadata(contentType: 'image/${file.extension}'),
          );

      String url = await upload.ref.getDownloadURL();
      return url;
    } catch (e) {
      print('error in uploading image for : ${e.toString()}');
      return '';
    }
  }

putData() 方法默认采用 Uint8List。

使用 TaskSnapshot 上传图像在我的 flutter web 项目上不起​​作用。 我用过 firebase_storage: ^8.1.3 。 以下代码适用于我的网络项目。

String nameImage = DateTime.now().millisecondsSinceEpoch.toString();

Reference _reference = FirebaseStorage.instance
        .ref()
        .child('images/$nameImage.png}');
    await _reference
        .putData(
      await image.readAsBytes(),
      SettableMetadata(contentType: 'image/jpeg'),
    )
        .whenComplete(() async {
      await _reference.getDownloadURL().then((value) {

        user.profilePictureURL = value;
        FireStoreUtils.firestore
          .collection(USERS)
          .doc(user.userID)
          .update({'profilePictureURL': user.profilePictureURL});

      });
    });