flutter filepicker upload to firebase cloud storage won't work

42 Views Asked by At
Future<String?> uploadImageOld () async {
  FilePickerResult? result = await FilePicker.platform.pickFiles();
  if (result != null) {
    final storageRef = FirebaseStorage.instance.ref();
    final images = storageRef.child('images');
    File file = File(result.files.single.path!);
    final filename = Path.basename(file.path);
    final uploadRef = images.child('images/$filename');
    await uploadRef.putFile(file);
    return await uploadRef.getDownloadURL();
  } else {
    return null;
  }
}

Trying to select a file and upload to firebase cloud storage, but it freeze after I select a file.

1

There are 1 best solutions below

0
Rainy sidewalks On

see upload-files and try below if works

Future<String?> uploadImageOld () async {
  FilePickerResult? result = await FilePicker.platform.pickFiles();
  if (result != null) {
    final metadata = SettableMetadata(contentType: "image/jpeg");// pass other meta data if needed
    final storageRef = FirebaseStorage.instance.ref();
   // final images = storageRef.child('images');
    File file = File(result.files.single.path!);
    final filename = Path.basename(file.path);
    final uploadRef =  storageRef.child('images/$filename');
   final uploadTask =await uploadRef.putFile(file);
   uploadTask.snapshotEvents.listen((TaskSnapshot taskSnapshot) {
    switch (taskSnapshot.state) {
      case TaskState.running:
        final progress =
            100.0 * (taskSnapshot.bytesTransferred / taskSnapshot.totalBytes);
        print("Upload is $progress% complete.");
        break;
      case TaskState.paused:
        print("Upload is paused.");
        break;
      case TaskState.canceled:
        print("Upload was canceled");
        break;
      case TaskState.error:
        // Handle unsuccessful uploads
        break;
      case TaskState.success:
        return await uploadRef.getDownloadURL();
        // Handle successful uploads on complete
        // ...
        break;
    }
  });
    //return await uploadRef.getDownloadURL();
  } else {
    return null;
  }
}