繁体   English   中英

如何将图像文件上传到Firebase存储并在Flutter web app中显示

[英]How to upload an image file to Firebase Storage and show it in the Flutter web app

再会,

我正在实施一个 function,用户可以将他们的照片上传到我的 Flutter Web 应用程序,该应用程序会显示它。

我正在尝试如下所示

  1. 当用户上传图片文件时,它被上传到 Firebase Storage as BYTES(我知道图片文件本身不能通过 Flutter WEB app 上传,必须转换为字节。是吗?)

  2. 字节文件的下载 URL 存储在 Firestore 中。

  3. 我的应用程序找到下载 URL 并使用 URL 显示图像文件(字节)(如果是)。

使用的方法是Image.network(downloadURL) ,但是好像url里面的文件必须是图片文件,否则会报错。

我想知道如何在 Flutter WEB 应用程序中显示从下载 URL 转换为 BYTES 的图像文件。

或者将图像文件本身上传到 Flutter WEB 应用程序中的 Firebase 存储。

应用程序使用以下代码找到下载 URL

  String? profileDownloadURL;

  @override
  initState() {
    super.initState();
    email = FirebaseAuth.instance.currentUser!.email;
    getProfileURL();
  }

  getProfileURL() async {
    DocumentSnapshot<Map<String, dynamic>> documentSnapshot =
        await FirebaseFirestore.instance.collection('Users').doc(email).get();
    setState(() {
      profileDownloadURL = documentSnapshot.data()!['profileDownloadURL'];
    });

    print('profile: $profileDownloadURL');
  }

用户可以使用以下方法 select 一个图像文件

  startWebFilePicker() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles();
    if (result != null) {
      final email = FirebaseAuth.instance.currentUser!.email;
      final storageRef = FirebaseStorage.instance.ref();
      final profileRef = storageRef.child(email!).child(result.files.single.name);
      try {
        // upload a byte-converted image file to Firebase Storage
        await profileRef.putData(result.files.single.bytes!);
        // update download URL on Firestore
        String downloadURL = await profileRef.getDownloadURL();
        FirebaseFirestore.instance.collection('Users').doc(email).set(
          {'profileDownloadURL': downloadURL},
          SetOptions(merge: true),
        );
      } on FirebaseException catch (e) {
        print('1: $e');
      } catch (e) {
        print('2: $e');
      }
    } else {
      // User canceled the picker
    }
  }

应用程序显示图像如下

Container(
  child: profileDownloadURL != null
    ? CircleAvatar(
        radius: 100,
        backgroundImage: Image.network(
          profileDownloadURL!,
          fit: BoxFit.fill,
        ).image,
      )
    : const CircleAvatar(
        radius: 100,
        child: Icon(
          Icons.person,
        ),
      ),
),

尝试使用发送元数据contentType: "image/jpeg" in await imageRef.putFile(selectedImagePath, metadata)

              try {
                final storageRef = FirebaseStorage.instance.ref();
                final imageRef = storageRef.child("no_image.jpg");
                final ImagePicker picker = ImagePicker();
                // Create file metadata including the content type

                XFile? image =
                    await picker.pickImage(source: ImageSource.gallery);

                if (image != null) {
                  File selectedImagePath = File(image.path);
                  var metadata = SettableMetadata(
                    contentType: "image/jpeg",
                  );
                  await imageRef
                      .putFile(selectedImagePath, metadata)
                      .whenComplete(() {
                    ShowSnack.showToast("File Uploaded...");
                  });
                } else {
                  ShowSnack.showToast("No file selected");
                }
              } on FirebaseException catch (e) {
                // ...
              }

查看结果

检查要点上的完整示例 - https://gist.github.com/akshaysinghhal/66e2ebaf61747040a76c62f826e8e8d1#file-upload_image-dart

要将文件上传到 Cloud Storage ,首先要创建对文件完整路径的引用,包括文件名。创建适当的引用后,然后调用 putFile()、putString() 或 putData( ) 方法将文件上传到 Cloud Storage。
可以在此处找到带有进度监控和错误处理的完整上传示例
此外,我建议您在 Flutter 中查看此线程 Firebase Cloud Storage
以下是一些类似实现的示例:

另请查看这些公共博客以获取更多示例;非 Google 官方博客:

FirebaseStorage storage = FirebaseStorage.instance;
Reference ref = storage.ref().child(pathname + DateTime.now().toString());
await ref.putFile(File(_image.path));
String imageUrl = await ref.getDownloadURL();
print(imageUrl);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM