Is it possible to upload pdf in firebase collection in Flutter.
How can download pdf from firebase
Firebase Realtime Database or Firebase Cloud Firestore can not host any file. But Firebase has a product called Cloud Storage that can host the files and actually keep reference to it in your Cloud Firestore.
What you need to do is to first upload the file and then get the URL of it and keep it in your Cloud Firestore:
Future<String> uploadFile(String filePath) async {
File file = File(filePath);
try {
await firebase_storage.FirebaseStorage.instance
.ref('uploads/bills.pdf')
.putFile(file);
String downloadURL = await firebase_storage.FirebaseStorage.instance
.ref('uploads/bills.pdf')
.getDownloadURL();
return downloadUrl;
} on firebase_core.FirebaseException catch (e) {
print(e);
}
}
Related
I upload one image from my computer to Firebase Storage and now I want that image to get in my Firebase database with his information and display it in my app. I can display information but cant display images. I google also but in every answer, they say first to upload the image to firebase storage from the app. then get his URL in the database and I don't want to upload from my app.
So if someone know then help.
You Can Get the download link for your image Like this
static final firebase_storage.FirebaseStorage storage =
firebase_storage.FirebaseStorage.instance;
String url = await storage
.ref('YourImagePath')
.getDownloadURL();
In addition to SARADAR21's excellent answer on how to get the data for a file at a known path, you can also list the files in Cloud Storage through the API, in case you don't know the path.
From that documentation:
final storageRef = FirebaseStorage.instance.ref();
final listResult = await storageRef.listAll();
for (var prefix in listResult.prefixes) {
// The prefixes under storageRef.
// You can call listAll() recursively on them.
}
for (var item in listResult.items) {
// The items under storageRef.
}
You can then use the references you get this way, and call getDownloadUrl() to get a download URL for each of them.
Future<QuerySnapshot?> getDataFromFirebase() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
FirebaseFirestore.instance
.collection('Images')
.get()
.then((QuerySnapshot? querySnapshot) {
querySnapshot!.docs.forEach((doc) {
List<dynamic> allImageData = doc["image_data"];
storeImageList = allImageData.map((i) => i.toString()).toList();
});
prefs.setStringList("imageList", storeImageList);
});
}
I am new to flutter and I am clueless on how to implement a function to download a PDF file from firebase. I went through multiple tutorials regarding downloading files from cloud storage to local storage in flutter app and still unable to make it work.
I want when user presses the button
onPressed: () async {},
Then, it will straight away download the file from my firebase cloud storage to their local files.
I know I have to use writeToFile, but how do I implement the function?
Hope you can help me, thanks!
When looking at the docs for Firebase Cloud Storage, you can download a file from the Cloud Storage to the local documents folder, by using the following function:
//You'll need the Path provider package to get the local documents folder.
import 'package:path_provider/path_provider.dart';
Future<void> downloadFileExample() async {
//First you get the documents folder location on the device...
Directory appDocDir = await getApplicationDocumentsDirectory();
//Here you'll specify the file it should be saved as
File downloadToFile = File('${appDocDir.path}/downloaded-pdf.pdf');
//Here you'll specify the file it should download from Cloud Storage
String fileToDownload = 'uploads/uploaded-pdf.pdf';
//Now you can try to download the specified file, and write it to the downloadToFile.
try {
await firebase_storage.FirebaseStorage.instance
.ref(fileToDownload)
.writeToFile(downloadToFile);
} on firebase_core.FirebaseException catch (e) {
// e.g, e.code == 'canceled'
print('Download error: $e');
}
}
You can find this, and read more about it on this page: https://firebase.flutter.dev/docs/storage/usage
To implement it on the onPressed funtion, i would suggest having the function in the same class as you have the button, and executing the function from the onPressed like this:
onPressed: () {
downloadFileExample();
}
I'm currently working on uploading multiple images to firebase and getting the downloadUrl into a list.
_imageList.forEach((element) async {
final StorageReference _ref = FirebaseStorage.instance
.ref()
.child("Users/ads/");
StorageUploadTask uploadTask =
_ref.putFile(element as i.File);
await uploadTask.onComplete;
print("Images uploaded");
String image_links = await _ref.getDownloadURL();
_imageUrls.add(image_links);// _imageUrls is a List
});
and now I wanna assign the _imageUrls into firestore.
Map<String, dynamic> ads = {
'adTitle': widget.title,
'adPrice': widget.price,
'adCategory': widget.dropdownValue,
'adCondition': this.newCondtionVal,
'adDesc': widget.desc,
'user_id': uID,
'imageUrls_List': _imageUrls,//Images goes hear
};
crudObj
.addData(ads)
.then((value) => {
showInSnackBar("dataAdded"),
})
.catchError((e) {
print(e);
});
But the problem is:uploading data to firestore works first(Image upload is not finished yet), So now imageUrls_List slot in firestore is empty.
Is there any way to add onComplete to the getDownloadURL() function?
or any other options to run the firestore upload after the images done with uploading?
I tried to upload the video using image picker to firebase storage and get the link but there's a problem!
At first, this is my upload video method:
Future<void> uploadVideo() async {
await ImagePicker.pickVideo(source: ImageSource.gallery).then((value) {
setState(() {
_video = value;
});
});
StorageReference storageReference = FirebaseStorage.instance
.ref()
.child('revisionVideos/${Path.basename(_video.path)}');
StorageUploadTask storageUploadTask = storageReference.putFile(
_video, StorageMetadata(contentType: 'video/mp4'));
await storageUploadTask.onComplete;
print('Video Uploaded');
storageReference.getDownloadURL().then((value) {
setState(() {
_videoUrl = value;
});
});
}
When I upload the video, there was a photo (there's an error when trying to preview it) not a video.
And in the run tab:
W/StorageUtil(17625): no auth token for request
W/NetworkRequest(17625): no auth token for request
W/StorageUtil(17625): no auth token for request
W/NetworkRequest(17625): no auth token for request
D/UploadTask(17625): Increasing chunk size to 1048576
Although I edited the rules in the storage and cloud firestore, too.
Add: I didn't add authentication page for this application and the firebase project is linked to 2 android apps.
I try to read listen to a stream from Firebase with this code:
visibleListsIds.forEach((final String listId) async {
final Stream<List<WishList>> wishListStream = sharedCollection()
.document(listId)
.snapshots()
.map((DocumentSnapshot documentSnapshot) {
log.d("updated Document Snapshot: ${documentSnapshot.data}");
return [
_getSerializers()
.deserializeWith(WishList.serializer, documentSnapshot.data)
];
});
wishListStreams.add(wishListStream);
});
Where sharedCollection() gives me access to the Firestore instance with the correct collection
I try to write to the collection, with this code
DocumentReference postRef = sharedCollection().document(wishList.listId);
firestore.runTransaction((Transaction tx) async {
DocumentSnapshot postSnapshot = await tx.get(postRef);
if (postSnapshot.exists) {
await tx.update(postRef,
_getSerializers().serializeWith(WishList.serializer, wishList));
} else {
await tx.set(postRef,
_getSerializers().serializeWith(WishList.serializer, wishList));
}
});
What happens:
I can write to Firebase but only one change at a time. When I do the next update, the last one gets reverted.
I can see the updated data only in the Firebase Console. The App does not show it and it does not show in the log at log.d("updated Document Snapshot: ${documentSnapshot.data}");.
When I modify data in the Firebase Console, I can also not see it change
BUT once I reload the App, all the Data syncs up to the current state of the Firebase Console
Anyone know why I do not get updates with the Stream?
Thanks for your help.
I use the Cloud Firestore Plugin:
cloud_firestore: ^0.13.0+1