简体   繁体   English

通过file_picker在flutter web中上传文件

[英]upload file in flutter web by file_picker

i use file_picker: ^4.2.0 show package for my application.我使用file_picker: ^4.2.0显示我的应用程序

when i get web release as html, get some Error.当我将网页发布为 html 时,会出现一些错误。

error: path always null in web release错误: path always null in web release

my code to get file:我获取文件的代码:

Future getFile() async {    
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      withReadStream: true,
      type: FileType.custom,
      allowedExtensions: ['png', 'jpeg', 'jpg', 'pdf'],
    );
    if (result != null) {
      PlatformFile file = result.files.single;
      setState(() {
        _file = File(file.path.toString());
        _filePath = file.path;
      });
      _uploadFile();
    } else {
      // file not choose
    }
  }

i use https://pub.dev/packages/file_picker but in flutter web path not suppor;我使用https://pub.dev/packages/file_picker但在 flutter web 路径中不支持;

you should to use bytes;你应该使用字节;

i save file bytes in var _fileBytes and use in request;我将文件字节保存在 var _fileBytes 中并在请求中使用;

var request = http.MultipartRequest('POST', Uri.parse('https://.....com'));
request.headers.addAll(headers);
request.files.add(
   http.MultipartFile.fromBytes(
     'image', 
      await ConvertFileToCast(_fileBytes),
      filename: fileName,
      contentType: MediaType('*', '*')
   )
);
request.fields.addAll(fields);
var response = await request.send();

function ConvertFileToCast:函数 ConvertFileToCast:

ConvertFileToCast(data){
  List<int> list = data.cast();
  return list;
}

it`s work for me :)它对我有用:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM