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

时间:2021-05-22 11:44:38

标签: flutter firebase-storage flutter-web

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

我可以使用 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 ';
    }
  } 

如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

您可以使用 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。