Flutter:如何将pdf文件上传到Firebase存储?

问题描述 投票:0回答:1

我正在使用Flutter应用程序,我想将PDF文件上传到Firebase存储中,我可以使用documents_picker来选择文件,但无法将其上传到存储中...请在此帮助我...我的代码如下

uploaddoc()async{


   dynamic docPaths;
   // Platform messages may fail, so we use a try/catch PlatformException.
   try {
     docPaths = await DocumentsPicker.pickDocuments;
     final Directory tempDir = Directory.systemTemp;
     final String fileName = "${Random().nextInt(10000)}.pdf";
     final File file = File('${tempDir.path}/$fileName');
     file.writeAsBytesSync(docPaths);

     final StorageReference ref = FirebaseStorage.instance.ref().child(fileName);
     final StorageUploadTask task = ref.putFile(file);
     final Uri downloadUrl = (await task.future).downloadUrl;
     _path = downloadUrl.toString();

     print(_path);
   } on PlatformException {

   }

   // If the widget was removed from the tree while the asynchronous platform
   // message was in flight, we want to discard the reply rather than calling
   // setState to update our non-existent appearance.
   if (!mounted)
     return;

   setState(() {
     _platformVersion = docPaths.toString();
   });


  }
firebase flutter firebase-storage flutter-layout
1个回答
1
投票

您可以使用此依赖项https://pub.dev/packages/file_picker将任何类型的文件上传到数据库。

final mainReference = FirebaseDatabase.instance.reference().child('Database');
Future getPdfAndUpload()async{
  var rng = new Random();
  String randomName="";
  for (var i = 0; i < 20; i++) {
    print(rng.nextInt(100));
    randomName += rng.nextInt(100).toString();
  }
  File file = await FilePicker.getFile(type: FileType.CUSTOM, fileExtension: 'pdf');
  String fileName = '${randomName}.pdf';
  print(fileName);
  print('${file.readAsBytesSync()}');
  savePdf(file.readAsBytesSync(), fileName);
}

Future savePdf(List<int> asset, String name) async {

  StorageReference reference = FirebaseStorage.instance.ref().child(name);
  StorageUploadTask uploadTask = reference.putData(asset);
  String url = await (await uploadTask.onComplete).ref.getDownloadURL();
  print(url);
  documentFileUpload(url);
  return  url;
}
void documentFileUpload(String str) {

  var data = {
    "PDF": str,
  };
  mainReference.child("Documents").child('pdf').set(data).then((v) {
  });
}

这样,您可以将文件上传到Firebase存储,并将URL插入实时数据库。

© www.soinside.com 2019 - 2024. All rights reserved.