How to delete a Firebase Storage file with flutter?

15,338

Solution 1

Update (2021-05-22):

FirebaseStorage.instance.refFromURL(url).delete() should be used now. getReferenceFromUrl that was suggested earlier seems to be gone from the API.

Update (2019-08-03):

According to this PR there is now a getReferenceFromUrl method in FlutterFire that allows looking up a storage reference by its download URL.


Previous answer:

On Android you can call getReferenceForUrl() to get a StorageReference from a download URL, and a similar method exists on iOS.

But I can't find a corresponding method in the FlutterFire reference docs. This unfortunately means that there is no way to map from a download URL back to a StorageReference in Flutter.

This sounds like an omission, so I recommend casting your +1 on this feature request.

For the moment this means you'll need to have the relative path to the file in Cloud Storage to be able to delete it from Flutter. With that path, your current code would work.

Solution 2

change filePath to

String filePath = 'https://firebasestorage.googleapis.com/v0/b/dial-in-21c50.appspot.com/o/default_images%2Fuser.png?alt=media&token=c2ccceec-8d24-42fe-b5c0-c987733ac8ae'
                  .replaceAll(new 
                  RegExp(r'https://firebasestorage.googleapis.com/v0/b/dial-in-21c50.appspot.com/o/default_images%2F'), '').split('?')[0];

FirebaseStorage.instance.ref().child(filePath).delete().then((_) => print('Successfully deleted $filePath storage item' ));

Solution 3

I have implemented a cleaner code but same as @earyhe, which is using Uri.decodeFull() and Path.basename(). Tried and it worked.

import 'package:path/path.dart' as Path;


  Future<void> deleteImage(String imageFileUrl) async {
  var fileUrl = Uri.decodeFull(Path.basename(imageFileUrl)).replaceAll(new RegExp(r'(\?alt).*'), '');


final StorageReference firebaseStorageRef =
    FirebaseStorage.instance.ref().child(fileUrl);
    await firebaseStorageRef.delete();
 }

Solution 4

3. 3. 2021

I am not sure how was it in the past (because I am quite new to Flutter and Firebase), but currently it is quite simple. Suppose you want to delete an image from Firebase Storage. In order to do that you will write the following method:

import 'package:firebase_storage/firebase_storage.dart';

//firebase Storage reference
  final _storage = FirebaseStorage.instanceFor(
      bucket: [your bucket address]);

Future<void> deleteImageFromDB(String imageUrl) async {
    var photo = _storage.refFromURL(imageUrl);
    await photo.delete();
  }

Solution 5

 if (post.imageURL != null) {
    StorageReference photoRef =
        await FirebaseStorage.instance.getReferenceFromUrl(post.imageURL);

    await photoRef.delete();
  }
Share:
15,338

Related videos on Youtube

codeThinker123
Author by

codeThinker123

Updated on September 14, 2022

Comments

  • codeThinker123
    codeThinker123 over 1 year

    I'm new to both Flutter and Firebase, so bear with me on this one.

    I am trying to delete a File in my Firebase Storage using the file Url.

    I have the full Url of the file and remove all characters excluding the file path.

    Then I try to delete the file. From following other answers on here I use the command; FirebaseStorage.instance.ref().child(filePath).delete()

    Below is my code;

    static void deleteFireBaseStorageItem(String fileUrl){
    
      String filePath = 'https://firebasestorage.googleapis.com/v0/b/dial-i-2345.appspot.com/o/default_images%2Fuser.png?alt=media&token=c2ccceec-8d24-42fe-b5c0-c987733ac8ae'
                      .replaceAll(new 
                      RegExp(r'https://firebasestorage.googleapis.com/v0/b/dial-in-2345.appspot.com/o/'), '');
    
      FirebaseStorage.instance.ref().child(filePath).delete().then((_) => print('Successfully deleted $filePath storage item' ));
    
    }
    

    The problem is the file never gets deleted.

    I think I have tracked down where the problem is.

    In the .delete() method there is a required 'app' and 'storageBucket' value.

    When I run this function the values are null.

    See screen shot

    I find this confusing because in the same file i see this;

    /// The [FirebaseApp] instance to which this [FirebaseStorage] belongs.
    ///
    /// If null, the default [FirebaseApp] is used.
    final FirebaseApp app;
    
    /// The Google Cloud Storage bucket to which this [FirebaseStorage] belongs.
    ///
    /// If null, the storage bucket of the specified [FirebaseApp] is used.
    final String storageBucket;enter code here
    

    From the documentation I can see maybe I need to use the 'Firebase core' plugin to make the app which links the bucket to that database. But there is not much specific to Dart & flutter.

    Does anyone have any experience with this?

    Found Temporary solution

    So there is not a method to convert the Url to a storage reference at the moment. Hopefully it will come out in a Firebase update.

    Here was my hack

     static void deleteFireBaseStorageItem(String fileUrl){
    
    String filePath = fileUrl
                      .replaceAll(new 
                      RegExp(r'https://firebasestorage.googleapis.com/v0/b/dial-in-2345.appspot.com/o/'), '');
    
    filePath = filePath.replaceAll(new RegExp(r'%2F'), '/');
    
    filePath = filePath.replaceAll(new RegExp(r'(\?alt).*'), '');
    
    StorageReference storageReferance = FirebaseStorage.instance.ref();
    
    storageReferance.child(filePath).delete().then((_) => print('Successfully deleted $filePath storage item' ));
    

    }

    I know.... i know....

    Ps 'dial-in-2345.appspot.com' is relevant to my app and you would need to change it.

    • Susmit
      Susmit about 5 years
      Thanks a lot for providing the temporary solution, I was stuck for two weeks, if it wasn't for your solution, I would had to wait till the much awaited feature comes up.
  • codeThinker123
    codeThinker123 over 5 years
    Hmmm. ok so from my code snippet above I have already manipulated the download Url by removing unwanted characters with Regex. This leaves behind the file path in the 'filePath' variable. I then pass this into the child argument of the function. In the image above, the '_pathComponents' list variable does not contain the full download Url, but the path.... which should be correct ...right?
  • Frank van Puffelen
    Frank van Puffelen over 5 years
    I'm not sure if there's a guarantee that the path to the image is 1:1 embedded in the download URL. I always treat the download URLs as opaque strings. But if you hard-coded the path to the image as default_images/user.png, does that work?
  • codeThinker123
    codeThinker123 over 5 years
    Frank you legend. YES!! that worked. Thank you so much. That's been bugging me for weeks! ok well it will be quite hard to manipulate that url string so i can dynamically delete files. I guess we all have to do that for now until the 'getReferenceForUrl()' feature is implemented. Cheers
  • BDL
    BDL over 3 years
    Although this code might solve the problem, a good answer should explain what the code does and how it helps
  • Jesswin
    Jesswin almost 3 years
    Thank you So Much, got this working answer after searching for hours!