我正在尝试制作一个图像上传按钮并将其链接到Firebase,以便每次按下该按钮时,图像都会发送到Firebase存储。以下是我的代码的相关片段:
// 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();}),
但是,每次按此按钮时,图像都会用相同的名称覆盖现有的图像,我想知道是否有一种方法可以使每次按该按钮时,图像的名称都会更改,并且结果,原始图像不会被覆盖。我非常感谢我所获得的任何帮助,因为我是Flutter和Firebase的新手。
谢谢!
基本上,当您致电:
FirebaseStorage.instance.ref().child('myimage.jpg');
您每次都上传具有相同名称的文件:
myimage.jpg
为了解决您的问题,您只需要为图像生成一个随机密钥即可。您可以通过以下几种方法执行此操作:
如果您设置了Firestore(Firebase提供的数据库),则可以将图像名称推送到数据库,并让其返回DocumentID,Firestore会为您创建一个未使用的随机ID。
您还可以使用当前的日期/时间:
DateTime.now().toString()
要么
DateTime.now().toIso8601String();
或者,当然,您始终可以根据要上传的文件名编写自己的哈希函数,具体操作如下:
_imageFile.toString();
然后,一旦获得文件的随机名称,就应该像这样上传:
FirebaseStorage.instance.ref().child(myImageName).putFile(_imageFile);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句