Flutter&Firebase - 修改个人资料图片时出现 Firebase 存储问题

问题描述 投票:0回答:1

我需要有关与 Firebase 链接的 Flutter 应用程序的帮助。这个应用程序有一个登录方法,我想要一张图片,用户可以随时更新它。

目前,我设法将 Firebase 存储文件中已存在的图片替换为从手机图库中拍摄的图片 (uploadFile)。另外,如果 Firebase 存储中已经存在这张图片,我还可以从 Firebase 存储中取回该图片 (getProfilImage)。

问题: 但是,当我想将应用程序中的新图片添加到 Firebase 存储时,Firebase 不允许我的用户使用新图片创建新文件,并且我的应用程序崩溃了。

如果有人可以帮助我更改用户的图片,而 Firebase 存储中尚未有此图片的文件,我将不胜感激

调试控制台错误

E/StorageException(17322): StorageException has occurred.
E/StorageException(17322): Object does not exist at location.
E/StorageException(17322):  Code: -13010 HttpResult: 404
E/StorageException(17322): {  "error": {    "code": 404,    "message": "Not Found."  }}
E/StorageException(17322): java.io.IOException: {  "error": {    "code": 404,    "message": "Not Found."  }}

将图像上传到Firebase Storage的功能: 注意:当 $currentUser 被替换为已经存在的文件时,代码将起作用

 Future uploadFile() async {
    Reference storageRef = storage.ref().child('UsersImageProfil/$currentUser.png'); 
    UploadTask uploadTask = storageRef.putFile(imageProfilFile!);
    await uploadTask.whenComplete(() {
       print('File uploaded');  
      setState(() {
              imageProfilFile = null;
            });  
    });
  }

从Firebase Storage获取图像的函数 注意:当 $currentUser 被替换为已经存在的文件时,代码将起作用

 void initState() {
    super.initState();
    getProfilImage();
  }

   getProfilImage() {
    Reference ref = storage.ref().child('UsersImageProfil/$currentUser.png');
    ref.getDownloadURL().then((downloadUrl) {
      setState(() {
        userPhotoUrl = downloadUrl.toString();
      });
    }).catchError((e) {
      setState(() {
        userPhotoUrl = defaultImageUrl;
      });
      print('Une erreur est survenue: ${e.error}');
    });
  }

显示图片的功能

class SetPhotoProfilState extends State<SetPhotoProfil> {
  File? imageProfilFile;
  final picker = ImagePicker();
  String? userPhotoUrl;
  String defaultImageUrl = 'https://svgsilh.com/png-1024/2098873.png';
@override
  Widget build(BuildContext context) {
    return Container(
        child: Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        ElevatedButton(
            style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(kColorPrimary)),
            onPressed: () async {
              Map<Permission, PermissionStatus> statuses = await [
                Permission.storage,
                Permission.camera,
              ].request();
              if (statuses[Permission.storage]!.isGranted &&
                  statuses[Permission.camera]!.isGranted) {
                showImagePicker(context);
              } else {
                print('No permission');
              }
            },
            child: Text("Modifier sa photo de profil")),
        userPhotoUrl == null
            ? CircleAvatar(
                radius: 42,
                backgroundColor: kColorPrimary,
                child: CircleAvatar(
                  radius: 40,
                  backgroundImage: NetworkImage(
                   defaultImageUrl, // Remplacez l'URL par le lien de votre image de profil
                  ),
                ),
              )
            : CircleAvatar(
                radius: 42,
                backgroundColor: kColorPrimary,
                child: CircleAvatar(
                    radius: 40, backgroundImage: NetworkImage(userPhotoUrl!)),
              ),
      ],
    ));
  }

showImagePicker 函数

  void showImagePicker(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (builder) {
          return Card(
            child: Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height / 5.2,
              margin: const EdgeInsets.only(top: 8.0),
              padding: const EdgeInsets.all(12),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Expanded(
                    child: InkWell(
                      child: Column(
                        children: [
                          Icon(Icons.image, size: 60.0),
                          SizedBox(
                            height: 12.0,
                          ),
                          Text(
                            'Gallerie',
                            textAlign: TextAlign.center,
                          )
                        ],
                      ),
                      onTap: () {
                        _imgFromGallery();
                        Navigator.pop(context);
                      },
                    ),
                  ),

   _imgFromGallery() async {
     await picker
        .pickImage(source: ImageSource.gallery, imageQuality: 50)
        .then((value) {
      if (value != null) {
        imageCache.clear();
      setState(() {
        imageProfilFile = File(croppedFile.path);
        convertImageToPNG();
        uploadFile(); 
      });
      }
    });
  }

另外我已经修改了存储规则:

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth != null;
    }
  }
}
flutter firebase dart firebase-authentication firebase-storage
1个回答
0
投票

尝试使用此规则更新您的规则

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth != null; // Allow authenticated users to read and write files
      allow create: if request.auth != null && request.resource.size < 10 * 1024 * 1024; // Allow files smaller than 10 MB to be created
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.