Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload image flutter web with dio formdata

I am trying using file_picker and dio packages to upload files as form data.

This is for flutter web and it seems MultipartFile.fromFile is not accepted.

What I tried is the following:

if (result != null) {    
  for (var file in result.files) {
    final formData = FormData.fromMap({
      ...someOtherData,
      'file': File(file.name), // <------ I guess this is where the issue is, I also tried file instead of File(file.name)
    });
    
    dio.post(
      url,
      data: formData,
    );
  }
}
like image 290
user3808307 Avatar asked May 28 '26 11:05

user3808307


1 Answers

If anyone is still wondering how to get it working on both mobile and web (This is using the image_picker's PickedFile as the image variable type) :

 FormData body;
 final bytes = await image.readAsBytes();
 final MultipartFile file = MultipartFile.fromBytes(bytes, filename: "picture");
 MapEntry<String, MultipartFile> imageEntry = MapEntry("image", file);
 body.files.add(imageEntry);

** The catch is that the filename is required on web and is automatically assigned on mobile.**

like image 147
HKTareen Avatar answered May 31 '26 13:05

HKTareen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!