【问题标题】:Flutter web - Uploading image to firebase storageFlutter web - 将图像上传到 Firebase 存储
【发布时间】:2021-08-11 09:38:56
【问题描述】:

我在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 ';
    }
  } 

如何解决这个问题?

【问题讨论】:

标签: flutter firebase-storage flutter-web


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 嘿,它不起作用。 “不支持的操作:无法从数据 URI 中提取文件路径” - 这是我得到的错误。 dart:io 不适用于基于浏览器的应用程序。这就是为什么我不能使用文件对象。
    猜你喜欢
    • 2021-07-28
    • 2020-04-30
    • 2018-10-24
    • 2019-01-22
    • 2020-12-20
    • 2021-07-03
    • 2021-03-29
    • 2022-07-28
    相关资源
    最近更新 更多