Home > Back-end >  Converting PlatformFile to File
Converting PlatformFile to File

Time:12-01

I am using the package file_picker to select a PDF file from the device and uploading it to a remote server.

 void capturarPDF() async{

    FilePickerResult? result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['pdf'],
    );

    if(result == null) return;

    PlatformFile file = result!.files.first ;
    print("file ${file.path}");

    _upload(file);

  }

  void _upload(File file) {

    if (file == null) return;
    setState(() {});
    String base64Image = base64Encode(file.readAsBytesSync());
    String fileName = file.path!.split("/").last;

    String? mimeStr = lookupMimeType(file.path.toString());
    var fileType = mimeStr!.split('/');
    var tipo = "3";

    http.post(Uri.parse(phpEndPoint), body: {
      "image": base64Image,
      "name": fileName,
      "cod_sat": widget.codigo,
      "tipo": tipo,
    }).then((res) async {

      setState(() {
      });
    }).catchError((err) {
      print(err);
    });
  }

My issue is that at line _upload(file); I am getting the error:

The argument type 'PlatformFile' can't be assigned to the parameter type 'File'

Is there a way to convert a PlatformFile generated by the package file_picker to the type File needed to upload the file?

CodePudding user response:

PlatformFile has a path reference to the file, you can take that path and set a File object with that path like this:

     final path = file.path
    _upload(File(path));
  • Related