【问题标题】:Upload and store image into firebase using flutter使用颤振将图像上传并存储到firebase
【发布时间】:2022-01-17 17:30:31
【问题描述】:

我正在尝试弄清楚用户如何上传例如个人资料图片并将此商店保存在 firebase 中。这是我到目前为止显示图像选择器的代码,但我无法获取路径也无法上传图像

dynamic _showSelectImageDialog() {
    return Platform.isIOS ? _iosBottomSheet() : _androidDialog();
  }

  Future _iosBottomSheet() async => showCupertinoModalPopup(
        context: context,
        builder: (context) {
          return CupertinoActionSheet(
            // title: Text('Add Photo'),
            actions: <Widget>[
              CupertinoActionSheetAction(
                onPressed: () => _upload(ImageSource.camera),
                child: const Text('Take Photo'),
              ),
              CupertinoActionSheetAction(
                onPressed: () => _upload(ImageSource.gallery),
                child: const Text('Choose Photo'),
              ),
            ],
            cancelButton: CupertinoActionSheetAction(
              onPressed: () => Navigator.pop(context),
              child: const Text('Cancel'),
            ),
          );
        },
      );

  _androidDialog() {
    showDialog(
      context: context,
      builder: (context) {
        return SimpleDialog(
          title: const Text('Add Photo'),
          children: <Widget>[
            SimpleDialogOption(
              onPressed: () => _upload(ImageSource.camera),
              child: const Text('Take Photo'),
            ),
            SimpleDialogOption(
              onPressed: () => _upload(ImageSource.gallery),
              child: const Text('Choose From Gallery'),
            ),
            SimpleDialogOption(
              onPressed: () => Navigator.pop(context),
              child: const Text(
                'Cancel',
                style: TextStyle(
                  color: Colors.redAccent,
                ),
              ),
            ),
          ],
        );
      },
    );
  }

  // Select and image from the gallery or take a picture with the camera
  // Then upload to Firebase Storage

  _upload(ImageSource source) async {
    var picker = ImagePicker();
    PickedFile pickedImage;
    try {
      pickedImage = (await picker.pickImage(source: source, maxWidth: 1920))
          as PickedFile;

      File imageFile = File(pickedImage.path);

      try {
        // Uploading the selected image with some custom meta data
        await storageRef
            .child('uploads/user/avatar/${widget.user.id}/$imageFile.jpg')
            .putFile(imageFile);
        print(imageFile);
        // Refresh the UI
        setState(() {});
      } on FirebaseException {
        // print(error);
      }
    } catch (err) {
      print(err);
    }
    Navigator.pop(context);
  }

_displayProfileImage() {
    // No new profile image
    if (_profileImage == null) {
      // No existing profile image
      if (widget.user.profileImageUrl.isEmpty) {
        // Display placeholder
        return AssetImage('assets/images/user_placeholder.jpg');
      } else {
        // User profile image exists
        return CachedNetworkImageProvider(widget.user.profileImageUrl);
      }
    } else {
      // New profile image
      return FileImage(File(_profileImage.path));
    }
  }

【问题讨论】:

    标签: firebase flutter file-upload firebase-storage


    【解决方案1】:

    1) 使用图像选择器选择图像

    把这个包放在你的 pubspec.yaml 中

    image_picker: ^0.8.4+4

    2) 使用此代码选择图片

    image = await _picker.pickImage(source: ImageSource.gallery);

    3) 将图片保存到firebase cloud并获取图片URL

    将这些包放在你的 pubspec.yaml 中

    cloud_firestore: ^3.1.0
    firebase_storage: ^10.1.0
    firebase_core: ^1.10.0
    

    使用此代码将图像上传到云存储

    var imageFile = File(image!.path);
                          String fileName = basename(imageFile.path);
                          FirebaseStorage storage = FirebaseStorage.instance;
                          Reference ref =
                              storage.ref().child("Image-" + productname.text);
    
    

    使用此代码获取 URL

    UploadTask uploadTask = ref.putFile(imageFile);
                          await uploadTask.whenComplete(() async {
                            var url = await ref.getDownloadURL();
                            image_url = url.toString();
                          }).catchError((onError) {
                            print(onError);
                          });
    

    4) 最后将图片url添加到firebase数据库

    将数据添加到 firebase 数据库的代码

    Map<String, dynamic> demodata = {
          "image_url": imageurl
        };
        CollectionReference collectionreference =
            FirebaseFirestore.instance.collection(image);
        collectionreference.add(demodata);
    

    【讨论】:

    • 这是否解决了您的问题?
    猜你喜欢
    • 1970-01-01
    • 2021-04-07
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 2021-04-03
    • 2021-02-26
    • 2017-09-25
    相关资源
    最近更新 更多