Get url download from firestore - firebase

i develop an apps where student can upload an audio into the system. But the audio uploaded need to display at the teacher side. My problem is, how i can get the url from the uploaded audio, so that the teacher can download the audio from the student. what should i do so that the teacher can download the url?
Future<List<DocumentSnapshot>> getAudioFile() async {
Map<String, dynamic> audios = {
"audio": audio,
};
var docRef = FirebaseFirestore.instance.collection("Audio");
QuerySnapshot query = await docRef.limit(10).get();
// if(query.size() > 0) {
// query.forEach((doc) async {
// http.Response downloadData = await http.get(doc.url);
// });
// }
return query.docs;
}
Future<String> urlDownload(file) async {
Reference ref = FirebaseStorage.instance.ref().child("files/");
UploadTask uploadTask = ref.putFile(file);
final Future<String> downloadUrl = ref.getDownloadURL();
final http.Response downloadData = await http.get(downloadUrl);
return downloadUrl;
}

after uploading file, get the url for that uploaded file
final url = FirebaseStorage.instance.ref().child("files/").child('filename').getDownloadURL();
after that you need to store that url on database/firestore,
now both teacher and student can access it via the stored url

this is the correct way of doing it as of July 15, 2021
final task = storageRef.lecturesStorage('fileTitle').putFile(file));
task.then((res) async {
// now you got the download url correctly
final downloadUrl = await res.ref.getDownloadURL();
// do something with it like putting it into a document
}

Related

Define Firebase cloud storage path in flutter

I am having trouble defining path for Firebase cloud storage.
I would like it to be -
user id -> firestore doc id -> folder's name.
currently, I successfully save the images in this way.
class FirebaseStorageService {
final String imageName;
FirebaseStorageService({required this.imageName});
get imageFileName =>
imageName + DateTime.now().millisecondsSinceEpoch.toString();
//get firestore doc id
final postid = FirebaseFirestore.instance.collection('properties').doc().id;
//get user id
final String? userid = FirebaseAuth.instance.currentUser!.uid;
//! Upload gallery
Future<String> saveGalleryInCloudStorage({
required File file,
}) async =>
await upload(
file: file,
path: '$userid/$postid/Property Gallery/$imageFileName',
contentType: 'image/png');
/// Generic file upload for any [path] and [contentType]
Future<String> upload({
required File file,
required String path,
required String contentType,
}) async {
final storageReference = FirebaseStorage.instance.ref().child(path);
final uploadTask = storageReference.putFile(
file, SettableMetadata(contentType: contentType));
final snapshot = await uploadTask;
final downloadUrl = await snapshot.ref.getDownloadURL();
return downloadUrl;
}
}
However, the problem I am having is the postid (that is used in firebase cloud storage path) is not same with firestore doc id.
How do I make them to be the same?
Thanks in advance!!
.collection('properties').doc()
the doc is empty hence firebase generates an auto id.
What you can do is Create an empty doc get a doc id, use the id to save the file, and when saving your firestore doc just update the empty doc
create empty doc
final documentReference = await FirebaseFirestore.instance.collection('mycoll').add({'id':''});
use doc id to save file obtained from
documentReference.id
makes this redudant
//get firestore doc id
final postid = FirebaseFirestore.instance.collection('properties').doc().id;
on done saving file , save your doc with the id above
FirebaseFirestore.instance.collection('properties').doc(documentReference.id)
.set(servicemodel.toJson());```
You can upload Image and update fields related withthis function. Its work for me.
static String staticImagePath= "";
final FirebaseAuth _auth = FirebaseAuth.instance;
File? file;
Future uploadImageToFirebaseStorage() async {
var _user = _auth.currentUser!.uid;
var _propertiesCollection= FirebaseFirestore.instance
.collection('Properties')
.where('postId', isEqualTo: _user);
var querySnapshots = await _propertiesCollection.get();
try {
var _image = await ImagePicker().pickImage(source: ImageSource.gallery);
file = File(_image!.path);
firebase_storage.Reference _refPath = firebase_storage
.FirebaseStorage.instance
.ref()
.child('MyImageRepo')
.child(_auth.currentUser!.uid);
firebase_storage.UploadTask _uploadTask = _refPath.putFile(file!);
String _url = await (await _uploadTask).ref.getDownloadURL();
staticImagePath = _url.toString();
await _propertiesCollection.doc(_auth.currentUser!.uid).update(({
'postId': staticImagePath,
}));
} catch (e) {
return Center(child: Text(e.toString()));
}
}

How to add multiple images in flutter (firebase)

how I can add multiple images and store them in an array in firebase ?
every container has a + button so the user can add single image per container then I WANT TO STORE them in my firebase
any help would be greatly appreciated ^^
what you are showing in your image is fbCloudStore which is use to store information in json structure.
To store the images you may use fbStorge.
here's an snippet I use on my project:
Future<String?> uploadFile({
required FilePickerResult file,
required String fileName,
required FirebaseReferenceType referenceType,
}) async {
try {
final ref = _getReference(referenceType);
final extension = path.extension(file.files.first.name);
final _ref = ref.child(fileName + extension);
late UploadTask uploadTask;
if (kIsWeb) {
uploadTask = _ref.putData(file.files.first.bytes!);
} else {
uploadTask = _ref.putFile(File(file.files.single.path!));
}
var url;
await uploadTask.whenComplete(
() async => url = await uploadTask.snapshot.ref.getDownloadURL());
print(url);
return url;
} on FirebaseException catch (_) {
print(_);
}
}
Note that I'm returning the URL of fbStorage in order to associate it with fbCloudStorage
final url =
await FirebaseStorageSer.to.uploadFile(
file: result,
fileName: STORAGE_USER_PROFILE_PICTURE,
referenceType: FirebaseReferenceType.user,
);
if (url != null) {
await FirebaseAuthSer.to
.updateUserProfile(photoUrl: url);
}
FirebaseReferenceType.user is just a simple enum to simplify ref targets.

Flutter Firebase Storage 0.5.0 upload file and video error

What I want to do: Upload a file and a video with Firebase Storage 0.5.0 and return url.
What current problem is: I can upload file and image with Firebase storage 0.5.0, but I can't return url. I also see my file and video uploaded in Firebase storage in Firebase console.
My code:
Future<String> _uploadFile(Reference ref, File file,
[SettableMetadata metadata]) async {
UploadTask uploadTask = ref.putFile(file, metadata);
uploadTask.whenComplete(() async {
try {} catch (onError) {
print("Error");
}
});
final url = await ref.getDownloadURL();
return url;
}
Future<String> uploadVideo(File video,
{String refName, SettableMetadata metadata}) async {
metadata = SettableMetadata(contentType: 'video/mp4');
final name = refName != null ? refName : path.basename(video.path);
final ref = _VideoRef.child(name);
return _uploadFile(ref, video, metadata);
}
Future<File> downloadImage(String imageUrl, String savePath) async {
final ref = _storage.ref(imageUrl);
var file = File(savePath);
await ref.writeToFile(file);
return file;
}
What the console told me:
FirebaseException (Firebase_storage/object-not-found). No object exist in desired reference.
How do I fix this?
Try the following:
uploadTask.whenComplete(() async {
try {
url = await ref.getDownloadURL();
} catch (onError) {
print("Error");
}
});
When the future completes, call getDownloadURL() to get the url.

Upload multi images to firestore using flutter and get it's download URLs and save all of URLs to firebase

I have a form that have images to upload , when the user try to press on "Submit" button i'm trying to upload list of images to firestore and get all of its URLs and then submit a form to "x" collection in firebase but the writing on "x" collocation done before upload the images and get it's URLs.
I thinks the problem with (async,await).
Appreciate to help me.
List<File> imagePaths= new List() ;
List<String> imageURL= new List() ;
Future<FirebaseUser> getUser() async {
return await _auth.currentUser();
}
Future<void> uploadPic(File _image) async {
String fileName = basename(_image.path);
StorageReference firebaseStorageRef =
FirebaseStorage.instance.ref().child(Random().nextInt(10000).toString()+fileName);
StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
var downloadURL = await(await uploadTask.onComplete).ref.getDownloadURL();
var url =downloadURL.toString();
imageURL.add(url); // imageURL is a global list that suppose to contain images URLs
print("\n ---------------------------\n downloadURL :"+ url);
print("\n ---------------------------\n imageURL :"+ imageURL.toString());
}
Submit(BuildContext context) {
//imagePaths is list of file
imagePaths.add(Front_image);
imagePaths.add(Back_image);
imagePaths.forEach((x) => {
uploadPic(x)
});
getUser().then((user) {
crudObj.addNew({
'uid': user.uid,
'name': name,
'images':imageURL,
}).then((result) {
Navigator.pop(context);
}).catchError((e) {
print(e);
});
});
}
You should call your Submit only once your upload task is complete. I would recommend implementing something like this:
Stream uploadImageToFirebaseStorage(File image, String fullPath) {
final StorageReference firebaseStorageRef =
FirebaseStorage.instance.ref().child(fullPath);
StorageUploadTask task = firebaseStorageRef.putFile(image);
return task.events;
}
And then listen to this Stream and only then submit:
uploadImageToFirebaseStorage(
image, 'path/imagename.jpg'
).listen((data) async {
StorageTaskEvent event = data;
if (data.type == StorageTaskEventType.success) {
String downloadUrl = await event.snapshot.ref.getDownloadURL();
await Submit(title, imageUrl: downloadUrl);
return true;
}
if (data.type == StorageTaskEventType.failure) return false;
});
Please take note that I did not re-write your code, I am sharing a possible implementation.

How to get the download URL from firebase with flutter?

I would like to retrieve the Download URL of a private image in firbase storage.
Hi have tried many of the suggestions on the site, but all of them end up in the same result.
I have tried the following code:
getImageNow() async {
StorageReference ref =
FirebaseStorage.instance.ref().child("/1.jpg");
String url = (await ref.getDownloadURL()).toString();
return url;
}
It works when i print the url inside the function, but when i try to call print(getImageNow())to get the url, i just get "Instance of 'Future<dynamic>'"
UPDATE*************
In the end i am trying to get somthing like this:
return Image.network(
getImageNow(),
);
But i can not get it to work with async.
Since getImageNow() is asynchronous (as indicated by the async keyword), you will need to use await to make the calling code wait for the result:
print(await getImageNow())
What await does here is that it essentially unwraps the Future and is equivalent to:
getImageNow().then((value) => print(value));
this is how i upload and get the download url
this part is how i get image from picker
Future getImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_image = image;
print('Image Path $_image');
});
}
then i upload it
Future uploadPic(BuildContext context) async {
String fileName = basename(_image.path);
StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child(fileName);
StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
final String url = (await taskSnapshot.ref.getDownloadURL());
print('URL Is $url');
}
hope it will help someone

Resources