How to create unique image ID each time upload is pressed using Flutter/Firebase?
Asked Answered
F

4

6

I'm trying to make an image upload button and link it to Firebase such that each time the button is pressed, the image is sent to Firebase Storage. Here are the relevant snippets of my code:

  // Files, and references
  File _imageFile;
  StorageReference _reference =
      FirebaseStorage.instance.ref().child('myimage.jpg');

  Future uploadImage() async {
    // upload the image to firebase storage
    StorageUploadTask uploadTask = _reference.putFile(_imageFile);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;

    // update the uploaded state to true after uploading the image to firebase
    setState(() {
      _uploaded = true;
    });
  }
  // if no image file exists, then a blank container shows - else, it will upload 
  //the image upon press
  _imageFile == null
                ? Container()
                : RaisedButton(
                    color: Colors.orange[800],
                    child: Text("Upload to Firebase Storage"),
                    onPressed: () {uploadImage();}),

However, each time I press this button, the image overwrites the pre-existing image with the same name, and I was wondering if there's a way to make it so that each time I press the button, the name of the image changes, and as a result the original image isn't overridden. I'd greatly appreciate any help I could get as I'm very new to Flutter and Firebase.

Thank you!

Fisc answered 6/4, 2020 at 17:29 Comment(2)
print(DateTime.now().toString()); could be possible solution.Horsy
Yes, that's possible. Thank you!Fisc
N
5

Basically, when you call:

FirebaseStorage.instance.ref().child('myimage.jpg');

You're uploading the file with the same name everytime:

myimage.jpg

In order to fix your problem, you just need to generate a random key for the image. There are a couple ways you could do this:

Ideally, you would use the Uuid package which is specifically for use-cases like this.

If you are set up with Firestore (the database that Firebase offers) then you can push the name of the image to the database, and have it return the DocumentID which Firestore will create a random ID for you that isn't used.

You could also use the current Date/Time (which would be considered a bad practice for major applications, but for a personal project it will serve you just fine):

DateTime.now().toString()

or

DateTime.now().toIso8601String();

Or of course, you can always write your own hashing function, based on the name of the file that you are uploading, which you would get by doing:

_imageFile.toString();

Then once you get the random name of the file, you should upload it like this:

FirebaseStorage.instance.ref().child(myImageName).putFile(_imageFile);
Nobility answered 6/4, 2020 at 18:2 Comment(0)
H
12

I think you're looking for a UUID generator.

Fortunately there is a packege for that : uuid

String fileID = Uuid().v4(); // Generate uuid and store it.

Now you can use postID as name for your file.

NOTE When you upload your file you may want to generate new uuid to avoid using the old one :)

One more thing: PLEASE dont use DateTime.now() think about if two users uploaded an image at the same time !!

Hypo answered 6/4, 2020 at 21:21 Comment(1)
I'll keep that in mind; I kept on seeing UUID as well. Thank you!Fisc
N
5

Basically, when you call:

FirebaseStorage.instance.ref().child('myimage.jpg');

You're uploading the file with the same name everytime:

myimage.jpg

In order to fix your problem, you just need to generate a random key for the image. There are a couple ways you could do this:

Ideally, you would use the Uuid package which is specifically for use-cases like this.

If you are set up with Firestore (the database that Firebase offers) then you can push the name of the image to the database, and have it return the DocumentID which Firestore will create a random ID for you that isn't used.

You could also use the current Date/Time (which would be considered a bad practice for major applications, but for a personal project it will serve you just fine):

DateTime.now().toString()

or

DateTime.now().toIso8601String();

Or of course, you can always write your own hashing function, based on the name of the file that you are uploading, which you would get by doing:

_imageFile.toString();

Then once you get the random name of the file, you should upload it like this:

FirebaseStorage.instance.ref().child(myImageName).putFile(_imageFile);
Nobility answered 6/4, 2020 at 18:2 Comment(0)
H
-1

This maybe a late answer but hope it helps someone in future,had the same challange my solution: I used DateTime.now().toString(),but before that i got the current logged in user UID from firebase,

then added it to every outgoing save to storage request like this DateTime.now().toString() + (_auth.currentUser!.uid), This made every file unique and solved the overwriting issue for me.

ARK*

Hereof answered 20/1, 2022 at 10:56 Comment(0)
T
-2

Simply Add a Document Reference

DocumentReference myDoc = FirebaseFirestore.instance
    .collection('COLLECTION')
    .doc();

myDoc having your new Document Id.

myDoc.set({'data':'test'});
Tideland answered 28/12, 2021 at 19:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.