9

I would like to send a picture as a multipart file to the server.

First I tried to use http.post :

var response = await http.post(
      Uri.parse('url.php'),
      headers:{ "Content-Type":"multipart/form-data" } ,
      body: {
        "fichier": base64img
      }
    );

I got this error :

Bad state: Cannot set the body fields of a Request with content-type "multipart/form-data".

Looking at the answers of this topic I tried to use the dio package :

var dio = Dio();
    var formData = FormData.fromMap({
      'fichier': await MultipartFile.fromFile(filePath, filename: 'upload')
    });
    var response = await dio.post(
      'url.php', 
      data: formData
    );

I got this error :

Error: Unsupported operation: MultipartFile is only supported where dart:io is available.

An issue as already been open here.

Finally, I try to use MultipartRequest from the http package :

var url = Uri.parse('url.php');
    var request = new http.MultipartRequest("POST", url);
    request.files.add(
      await http.MultipartFile.fromPath(
        "fichier", 
        filePath
      )
    );
    request.send().then((response) => print(response));

Got the same exact same error than with the dio package.

If anyone as a solution, I would gladly take it.

JS1
  • 631
  • 2
  • 7
  • 23

1 Answers1

16

Use http package and get image using fromBytes intead fromPath:

final uri = Uri.parse('https://myendpoint.com');
var request = new http.MultipartRequest('POST', uri);
final httpImage = http.MultipartFile.fromBytes('files.myimage', bytes,
    contentType: MediaType.parse(mimeType), filename: 'myImage.png');
request.files.add(httpImage);
final response = await request.send();
Rubens Melo
  • 3,111
  • 15
  • 23
  • Thanks for your answer, out of curiosity what does this part do : contentType: MediaType.parse(mimeType) and where it is defined ? Btw, tried without this part and works well. – JS1 Mar 10 '22 at 14:31
  • 1
    It is just a metadata from any file. You dont need it. – Rubens Melo Mar 10 '22 at 14:48
  • 1
    Where do you add the name of the field in this method? In context of the question, `fichier` is what I am referring to – letsintegreat Jan 07 '23 at 19:56
  • please look at https://stackoverflow.com/questions/75567634/flutter-await-sometimes-not-working-async-ontap after upload i need return response body in Future – MrSalesi Feb 26 '23 at 16:01