Home > OS >  upload image by flutter in firebase Storage
upload image by flutter in firebase Storage

Time:06-08

I try to upload an image on firebase storage and get the error.

Future selectImage(ImageSource source) async {
    try {
      XFile? xImage = await ImagePicker().pickImage(source: source);//getting picture from phone
      if(xImage == null ) return 'there is no image';
      final File file = File(xImage.path);
      //final Image image = Image.file(File(xImage.path));

      print(xImage.path);
      Directory appDocDir = await getApplicationDocumentsDirectory();
      String filePath = '${appDocDir.absolute}/file-to-upload.png';
      print(filePath);

      final storageRef = FirebaseStorage.instance.ref().child("UsersProfilePhoto/");

      await storageRef.putFile(file);
    } on FirebaseException catch (e) {
      print(e.message);
    }
  }

CodePudding user response:

Try like this.

Future selectImage(ImageSource source) async {
        try {
          ImagePicker imagePicker = ImagePicker();
          XFile pickedFile = await imagePicker.pickImage(source: source,   imageQuality: 80);
          File imageFile = File(pickedFile.path);
          if(imageFile == null ) return 'there is no image';
          print(imageFile.path);
          String fileName = DateTime.now().millisecondsSinceEpoch.toString();
    
          final storageRef = FirebaseStorage.instance.ref().child("UsersProfilePhoto/");
    
          await storageRef.putFile(imageFile);
        } on FirebaseException catch (e) {
          print(e.message);
        }
      }

CodePudding user response:

Try this

    import 'package:path/path.dart' as Path1;//for storing image path in firestore
    
    DatabaseReference reference = FirebaseDatabase.instance.reference();
    FirebaseStorage storage = FirebaseStorage.instance;
    File? fileImage;
    
    //call this function for picking image
    pickedImage() async{
        PickedFile? file = await ImagePicker().getImage(
            source: ImageSource.camera,
            maxHeight: 1000,
            maxWidth: 1000
        );
    
        File image = file!.path;
       
        setState((){
          fileImage = image;
        });
    
      }
    
//call this function for storing image in firestore
     _storeImage() async{
        Reference storagerefrence = storage.ref().child('card_images/${Path1.basename(fileImage!.path)}');
        TaskSnapshot uploadTask = await storagerefrence.putFile(fileImage!);
        String url = await storagerefrence.getDownloadURL();//download url from firestore and add to firebase database
    
        reference.child("image").push().set({
          'image' : url
        });
    }
  • Related