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

Posted

技术标签:

【中文标题】Flutter:如何将pdf文件上传到firebase存储?【英文标题】:Flutter: how can upload pdf file to firebase storage? 【发布时间】:2019-02-10 22:49:27 【问题描述】:

我正在开发一个 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();
   );


  

【问题讨论】:

【参考方案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插入实时数据库。

【讨论】:

以上是关于Flutter:如何将pdf文件上传到firebase存储?的主要内容,如果未能解决你的问题,请参考以下文章

Flutter:我正在使用 post api 将文件上传到数据库。但它给了我一个错误

如何把PDF文档上传到网上

如何上传pdf文件

在 Flutter 中,如何将文件上传到 PubNub 频道?

如何将 PDF 文件上传到 Parse 服务器?

身份验证在 FirebaseStorage Flutter 中不起作用