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.

1 Answer 1

18

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();
Sign up to request clarification or add additional context in comments.

5 Comments

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.
It is just a metadata from any file. You dont need it.
Where do you add the name of the field in this method? In context of the question, fichier is what I am referring to
please look at stackoverflow.com/questions/75567634/… after upload i need return response body in Future<String>
@RubensMelo getting error if i recall this after refreshing the token on token expire.ie, same request can't send twice.Any solution??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.