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!
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.
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.
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>:
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.
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 !!
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With