upload file in flutter web by file_picker

Issue

i use file_picker: ^4.2.0 show package for my application.

when i get web release as html, get some Error.

error: 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
    }
  }

Solution

i use https://pub.dev/packages/file_picker but in flutter web path not suppor;

you should to use bytes;

i save file bytes in var _fileBytes and use in request;

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(data){
  List<int> list = data.cast();
  return list;
}

it`s work for me 🙂

Answered By – Mehrdad Shirvan

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *