0

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
  • 261
  • 2
  • 9

1 Answers1

1

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
  • 2,563
  • 14
  • 22
  • 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
  • It is just a metadata from any file. You dont need it. – Rubens Melo Mar 10 '22 at 14:48