使用文件选择器将PlatformFile变成Flutter中的文件

Shi*_*vil 13 filepicker flutter firebase-storage flutter-dependencies

我正在使用文件选择器插件从设备中选择文件。该文件是在 PlatformFile 的数据类型中选择的,但我想将该文件发送到 Firebase Storage,并且我需要一个常规文件。如何将 PlatformFile 转换为文件以便将其发送到 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;
    }
  }
Run Code Online (Sandbox Code Playgroud)

小智 17

尝试这个:

PlatformFile pdf;
final File fileForFirebase = File(pdf.path);
Run Code Online (Sandbox Code Playgroud)

快乐编码!:)

  • 这在 Flutter Web 上不起作用,因为“PlatformFile.path”在 Web 上不可用。 (5认同)