Home > Software design >  How to send multipart file with Flutter
How to send multipart file with Flutter

Time:03-10

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.

CodePudding user response:

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();
  • Related