Search code examples
firebaseflutterdartgoogle-cloud-firestoreunique-id

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


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!


Solution

  • 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);