3

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,
    );
  }
}

2 Answers 2

5

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.**

Sign up to request clarification or add additional context in comments.

2 Comments

I get this error: Unsupported operation: _Namespace.
The docs should say that filename is required on web I didn't know why I was getting an exception. Thanks bro!
3

Ok, I found it, leaving here for someone having the same problem

if (result != null) {    
  for (var file in result.files) {
    final formData = FormData.fromMap({
      ...someOtherData,
      'file': MultipartFile.fromBytes(file.bytes as List<int>)
    });
    
    dio.post(
      url,
      data: formData,
    );
  }
}

2 Comments

I get this error: Unsupported operation: _Namespace.
Can you share your Code here, this works for web and mobile both.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.