Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 711
Zakenmaru Avatar asked Apr 06 '20 17:04

Zakenmaru


People also ask

How to upload image to Firebase Storage in flutter?

How to Upload Image to Firebase Storage In Flutter? When you select an image with the image picker, it returns a File, you can use await to wait until the user selects a file then store it as a File. Here is some sample code of how you can get the file from the image picker and upload it to Firebase.

How to add images to your Firebase website?

You can add images by drag and drop the images into the assets folder or simply copy-paste the images. The images that I used in this tutorial can be found here:- Images After setting up images, let’s work on the Firebase console.

How to add image_picker and Firebase_Storage?

Add firebase_storage, image_picker, path_provider, path and their versions to the dependencies section in your pubspec.yaml file: With the image_picker plugin, we have to do some extra setups for iOS and Android. Go to <your-project>/ios/Runner/Info.plist and add the following between <dict> and </dict>:

How to add a unique key to a Firebase Database?

So for adding data, use only uniqueKeyRef reference. So, using this code you'll create a unique id only once. You'll be able to add those childs under a single id. If you want another key, see UUID which can help you generate unique keys for your Firebase database without having to use the push () method. Show activity on this post.


2 Answers

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 !!

like image 128
Abdelbaki Boukerche Avatar answered Oct 11 '22 06:10

Abdelbaki Boukerche


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);
like image 5
asterisk12 Avatar answered Oct 11 '22 05:10

asterisk12