如何将file_picker生成的PlatformFile转换为File以上传PDF?
问题:将file_picker的PlatformFile转换为File类型实现PDF上传
我正在使用file_picker包从设备中选择PDF文件并上传至远程服务器,代码如下:
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); }); }
但在调用_upload(file);时出现错误:
The argument type 'PlatformFile' can't be assigned to the parameter type 'File'
请问是否有办法将file_picker生成的PlatformFile转换为上传所需的File类型?
解决方案
方法1:通过文件路径转换(非Web平台)
针对Android、iOS等有本地文件路径的平台,直接利用PlatformFile的path属性创建dart:io的File实例即可:
修改capturarPDF方法:
void capturarPDF() async{ FilePickerResult? result = await FilePicker.platform.pickFiles( type: FileType.custom, allowedExtensions: ['pdf'], ); if(result == null) return; PlatformFile platformFile = result.files.first ; print("file ${platformFile.path}"); // 转换为File类型,需先判断path不为空 if(platformFile.path != null){ File file = File(platformFile.path!); _upload(file); } }
原_upload方法无需修改,可直接使用。
方法2:跨平台兼容方案(支持Web)
如果需要适配Web平台,PlatformFile不会返回本地路径,但会提供文件字节数据bytes。可以直接基于字节数据处理,无需转换为File,同时调整_upload方法以兼容:
// 修改_upload方法,参数改为PlatformFile void _upload(PlatformFile file) { if (file.bytes == null) return; setState(() {}); // 直接使用PlatformFile的bytes进行base64编码 String base64Image = base64Encode(file.bytes!); // 直接使用PlatformFile的name属性获取文件名,无需拆分路径 String fileName = file.name; 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); }); } // 调整capturarPDF方法,开启withData以获取文件字节(Web平台必需) void capturarPDF() async{ FilePickerResult? result = await FilePicker.platform.pickFiles( type: FileType.custom, allowedExtensions: ['pdf'], withData: true, // 开启后可获取file.bytes,Web平台必须设置 ); if(result == null) return; PlatformFile file = result.files.first ; _upload(file); }
这种方案无需依赖文件路径,可在所有平台正常运行。
内容的提问来源于stack exchange,提问作者mvasco
相关产品推荐
相关产品推荐

