How to send multipart file with Flutter
Asked Answered
C

1

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.

Clemmy answered 10/3, 2022 at 12:36 Comment(0)
L
17

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();
Lionfish answered 10/3, 2022 at 13:58 Comment(5)
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.Clemmy
It is just a metadata from any file. You dont need it.Lionfish
Where do you add the name of the field in this method? In context of the question, fichier is what I am referring toFulfil
please look at #75568134 after upload i need return response body in Future<String>Blithe
@RubensMelo getting error if i recall this after refreshing the token on token expire.ie, same request can't send twice.Any solution??Leprous

© 2022 - 2024 — McMap. All rights reserved.