Kumaresan Jackie
Kumaresan Jackie

Reputation: 111

How to upload pdf file to firebase storage and get the url in flutter?

I am try to upload the pdf file to FirebaseStorage then get the download url. I'm Using file_picker: ^5.2.0+1 to pick the pdf file. The problem is upload tho firebase storage it told FilePicker can't assign the File. I tried several ways but it won't work.

FilePickerResult? result = await FilePicker.platform.pickFiles();

          if (result != null) {
            Uint8List? fileBytes = result.files.first.bytes;
            print(fileBytes);
            String fileName = result.files.first.name;
            print(fileName);
            await FirebaseStorage.instance.ref('uploads/jk').putData(fileBytes);
          }

Upvotes: 0

Views: 974

Answers (1)

Mujtaba
Mujtaba

Reputation: 11

this will do it for you, pick the file you want from the device you are using, upload it to firebase storage and get the download Url once done, assuming you are working with a statefulwidget

var url;
onTap() async {

//this will open up the device filePicker              
                File pdf;
                var pickedFile = await FilePicker.platform.pickFiles();

                if (pickedFile != null) {
                  pdf = File(pickedFile.files.single.path!);
///this will upload the pickedfile to firebase storage with the specified name in the .child() 
                  await FirebaseStorage.instance
                      .ref()
                      .child('pdf')
                      .putFile(pdf);
                }
///this part will fetch the download Url from firebase storage
///make sure to correctly specify the name of the file you want
                FirebaseStorage.instance
                    .ref()
                    .child('pdf')
                    .getDownloadURL()
                    .then((value) => setState(() {url = value;});         
              },

the url variable will obtain the value returned from the method which is the download url of your file

Upvotes: 1

Related Questions