How to upload pdf to firebase storage with flutter? - firebase

I'm using latest firebase_storage version now some methods and references of storage are updated ploadTask.onComplete does not support.
so how do I get uploaded pdf url?
Piece of code:
Future<String> uploadPdfToStorage(File pdfFile) async {
try {
Reference ref = FirebaseStorage.instance.ref().child('pdfs/${DateTime.now().millisecondsSinceEpoch}');
UploadTask uploadTask = ref.putFile(pdfFile, SettableMetadata(contentType: 'pdf'));
String downloadUrl = await (await uploadTask.onComplete).ref.getDownloadURL();
final String url = await downloadUrl;
print("url:$url");
return url;
} catch (e) {
return null;
}
}

Here's an edited code that should work with the latest firebase storage_package:
Future<String> uploadPdfToStorage(File pdfFile) async {
try {
Reference ref =
FirebaseStorage.instance.ref().child('pdfs/${DateTime.now().millisecondsSinceEpoch}');
UploadTask uploadTask = ref.putFile(pdfFile, SettableMetadata(contentType: 'pdf'));
TaskSnapshot snapshot = await uploadTask;
String url = await snapshot.ref.getDownloadURL();
print("url:$url");
return url;
} catch (e) {
return null;
}
}

Related

How to get the url from Firebase Storage file?

I want to retrieve the URL of a Uint8List image from firebase storage. But I am not able to do that. It prints a snapshot, not the url. Please help.
my code:
void _storeSignature() async {
try {
final Uint8List? signature = await exportSignature();
final FirebaseStorage? storage = FirebaseStorage.instance;
final String? pictureUrl =
"signature/${DateTime.now().millisecondsSinceEpoch.toString()}.png";
final ref = storage!.ref().child(pictureUrl!);
final uploadTask = ref.putData(signature!);
final downurl = await uploadTask.whenComplete(() {
return ref.getDownloadURL();
});
final url = downurl.toString();
print(url);
} catch (e) {
rethrow;
}
}
You have to await for the URL when calling ref.getDownloadURL()
change
return ref.getDownloadURL();
into
return await ref.getDownloadURL();
The UploadTask class extends Future, so you can also use await there already:
await ref.putData(signature!);
final downurl = await ref.getDownloadURL();
final url = downurl.toString();

How I can view my uploaded pdf from firebase storage with flutter?

I have recently uploaded a pdf file to firebase storage via picking a pdf by file_picker plugin.
now file is uploaded successfully :
but when I go to firebase storage : tapped on that pdf link , showing ERROR MESSAGE failed to load pdf decoument
Code for picking pdf via file_picker
void sendPdf() async {
FilePickerResult result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf'],
);
if(result != null) {
File file = File(result.files.single.path);
_storageMethods.uploadPdf(
pdf: file,
uploaderId: widget.adminUser.uid,
courseTitle:_courseTitleController.text,
coursePrice:_coursePriceController.text,
uploadProvider: _uploadProvider);
} else {
// User canceled the picker
}
}
Code for uploading a file to firebase storage:
Future<String> uploadPdfToStorage(File pdfFile) async {
try {
Reference ref = FirebaseStorage.instance.ref().child('pdfs/${DateTime.now().millisecondsSinceEpoch}');
UploadTask uploadTask = ref.putFile(pdfFile, SettableMetadata(contentType: 'pdf'));
TaskSnapshot snapshot = await uploadTask;
String url = await snapshot.ref.getDownloadURL();
print("url:$url");
return url;
} catch (e) {
return null;
}
}
Have found the issue with contentType
UploadTask uploadTask = ref.putFile(pdfFile, SettableMetadata(contentType: 'pdf'));
I've replaced with:
UploadTask uploadTask = ref.putFile(pdfFile, SettableMetadata(contentType: 'application/pdf'));

how to get image URL form firebase storage to firestore

i am trying to upload the image to firebase and get the URL in firestore. It does upload the image but it does not get the URL to Firestore.
this is how i get the image.
Future getImage1() async {
// ignore: deprecated_member_use
var firstImage = await ImagePicker.pickImage(
source: ImageSource.gallery, imageQuality: 65);
setState(() {
_image1 = firstImage;
});
}
this is how i upload and get the url.
uploadPic() async {
Reference ref = storage.ref().child("image1" + DateTime.now().toString());
UploadTask uploadTask = ref.putFile(_image1);
uploadTask.then((res) {
String url = res.ref.getDownloadURL().toString();
imageUrl1 = url;
return url;
});
}
this is how i get the link in firestore
"image 1 Url":(_image1 != null) ? await uploadPic() : null,
getDownloadURL is a Future, so how about you try it like this:
Future<String> uploadPic() async {
Reference ref = storage.ref().child("image1" + DateTime.now().toString());
UploadTask uploadTask = ref.putFile(_image1);
String url;
await uploadTask.whenComplete(() {
res.ref.getDownloadURL().then((fileUrl){
url = fileUrl as String;
});
});
return url;
}

Flutter Firebase upload multiple images

Uploading multiple images and waiting for the URL list, images were loaded to firestore successfully after few seconds and returns the url but before that the future function returns with null
Future<List<dynamic>> uploadImage() async {
_imageFile.forEach((image) async {
String rannum = Uuid().v1();
StorageReference reference =
FirebaseStorage.instance.ref().child('Reviews').child(rannum);
StorageUploadTask uploadTask = reference.putFile(image);
StorageTaskSnapshot downloadUrl = (await uploadTask.onComplete);
String _url = await downloadUrl.ref.getDownloadURL();
_urllist.add(_url);
});
return _urllist;
}
You have to call your function like this:
uploadImage(_imageFile).then((List<String> urls) => urls.forEach((element) => print(element)))
And I also changed your function:
Future<List<String>> uploadImage(List<File> _imageFile) async {
List<String> _urllist = [];
await _imageFile.forEach((image) async {
String rannum = Uuid().v1();
StorageReference reference =
FirebaseStorage.instance.ref().child('Reviews').child(rannum);
StorageUploadTask uploadTask = reference.putFile(image);
StorageTaskSnapshot downloadUrl = await uploadTask.onComplete;
String _url = await downloadUrl.ref.getDownloadURL();
_urllist.add(_url);
});
return _urllist;
}
also I don't understand why you enclosed with brackets "await uploadTask.onComplete"

How to Load Image to Firebase Storage and get downloadUrl (Flutter/Firebase)

I want to implement sending files to Firebase Storage, as well as get a link to it. But for some reason it does not work ...
void _pickFile() async {
File file = await FilePicker.getFile(type: FileType.ANY);
StorageReference ref = FirebaseStorage.instance.ref()
.child("image${Random().nextInt(999)}.jpg");
var fileUrl = ref.putFile(file).onComplete.then((file) =>
file.ref.getDownloadURL());
print(fileUrl);
_sendMessage(fileUrl: fileUrl.toString());
}
...
prefixIcon: IconButton(
icon: Icon(Icons.attach_file),
color: Colors.white,
onPressed: () => _pickFile()
)
Why do I get this instead of a link?
I/flutter (16610): Instance of 'Future'
I need a link in the String!
What is the problem?
Like the log say, fileUrl is a Future who is not resolved yet. You should make sure it's resolve to make use of the string give.
void _pickFile() async {
File file = await FilePicker.getFile(type: FileType.ANY);
StorageReference ref = FirebaseStorage.instance.ref()
.child("image${Random().nextInt(999)}.jpg");
String fileUrl = await (await ref.putFile(file).onComplete).ref.getDownloadURL();
print(fileUrl);
_sendMessage(fileUrl: fileUrl.toString());
}
You need use await for Future functions
void _pickFile() async {
File file = await FilePicker.getFile(type: FileType.ANY);
StorageReference ref = FirebaseStorage.instance.ref()
.child("image${Random().nextInt(999)}.jpg");
final StorageUploadTask uploadTask = ref.putFile(file);
StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
String downloadUrl = await taskSnapshot.ref.getDownloadURL();
_sendMessage(fileUrl: downloadUrl);
}
It would look like this without using await
void _pickFile() async {
File file = await FilePicker.getFile(type: FileType.ANY);
StorageReference ref = FirebaseStorage.instance.ref()
.child("image${Random().nextInt(999)}.jpg");
ref.putFile(file).onComplete.then((file){
var fileUrl = file.ref.getDownloadURL());
_sendMessage(fileUrl: fileUrl.toString());
});
}
here is my solution to upload and get the uploaded image url
first i get image with image picker
Future getImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_image = image;
print('Image Path $_image');
});
}
then i upload to firebase
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');
setState(() {
print("Profile Picture uploaded");
print("....................$url");
Scaffold.of(context).showSnackBar(
SnackBar(content: Text('Profile Picture Uploaded')));
});
}
this is the part i get the downloadUrl of currently uploaded image
final String url = (await taskSnapshot.ref.getDownloadURL());
print('URL Is $url');

Resources