【问题标题】:Make PlatformFile into File in Flutter using File Picker使用 File Picker 在 Flutter 中将 PlatformFile 制作成 File
【发布时间】:2021-03-23 23:42:43
【问题描述】:

我正在使用文件选择器插件从设备中选择文件。该文件是在 PlatformFile 的数据类型中选择的,但我想将文件发送到 Firebase 存储,我需要一个常规文件。如何将 PlatformFile 转换为 File 以便将其发送到 Firebase Storage?代码如下:

PlatformFile pdf;
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

void _trySubmit() async {
    final isValid = _formKey.currentState.validate();
    if (isValid) {
      _formKey.currentState.save();
      final ref = FirebaseStorage.instance
          .ref()
          .child('article_pdf')
          .child(title + '-' + author + '.pdf');
      await ref.putFile(pdf).onComplete; // This throws an error saying that The argument type 'PlatformFile' can't be assigned to the parameter type 'File'
    }
  }

void _pickFile() async {
    FilePickerResult result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['pdf'],
    );
    if (result != null) {
      pdf = result.files.first;
    }
  }

【问题讨论】:

    标签: flutter firebase-storage flutter-dependencies filepicker


    【解决方案1】:

    试试这个:

    PlatformFile pdf;
    final File fileForFirebase = File(pdf.path);
    

    编码愉快! :)

    【讨论】:

    • 这在 Flutter Web 上不起作用,因为 PlatformFile.path 在 Web 上不可用。
    • @lenz - 也许,我只在移动设备(Androis 和 IOS)上使用过它。
    • @RobertRobinson 它可以在网络上运行,你必须添加我认为的路径、名称和大小。
    【解决方案2】:

    如果您使用的是网络应用程序,则可以使用 flutter_file_picker 将图像文件发布到 Firestore:(取自常见问题解答页面):https://github.com/miguelpruivo/flutter_file_picker/wiki/FAQ

    // get file
    final result = await FilePicker.platform.pickFiles(type: FileType.any, allowMultiple: 
    false);
    
    if (result.files.first != null){
      var fileBytes = result.files.first.bytes;
      var fileName = result.files.first.name;
    
      // upload file
      await FirebaseStorage.instance.ref('uploads/$fileName').putData(fileBytes);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-13
      • 2012-10-02
      • 1970-01-01
      • 1970-01-01
      • 2010-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多