0

I have a json object and a multipartfile that a want to send to a server using multipartrequest in flutter,the multipartfile is good to go but the issue is that the request fields only accept string and I want to send a json object.

 request.fields["objectField"] = entrepriseAgricultureCharegement.toJson(); // this line does not work because the field cant take a json object.
 request.files.add(multipartFile);

here is the full function :

 Future syncLocalDataToMobileSig(
      {required EntrepriseAgricultureCharegement
          entrepriseAgricultureCharegement}) async {
    Uri uri = Uri.parse("$baseUrlMobile/new");

    var request = http.MultipartRequest("POST", uri);
    request.headers.addAll({"Content-Type": "multipart/form-data"});
    File file = File(
        "/data/user/0/com.example.app_amee/app_flutter/IMG_20220115_113910.jpg");
    var stream = http.ByteStream(file.openRead());
    stream.cast();
    var length = await file.length();
    var multipartFile = http.MultipartFile(
      "files",
      stream,
      length,
    );
   
    request.fields["objectField"] = entrepriseAgricultureCharegement.toJson();
    request.files.add(multipartFile);

    try {
    var streamedResponse = await request.send();
    final responseData = await streamedResponse.stream.toBytes();
    final responseString = String.fromCharCodes(responseData);
    print(responseString);
    } catch (e) {
      print("e => $e");
    }
  }

does anyone have the solution to send the json object using multipartrequest

3 Answers 3

1

I was able to send a file as MultiPart method by using the following code

static Future<ResponseStatusModel?> uploadAvatar(File file, String userId, List<String> activeAvatar) async {
print('uploadAvatar is called $activeAvatar');

ResponseStatusModel? responseModel;

print('avatar file path on profile API ${file.path} ');

try {
  var formData = FormData.fromMap({
    'userid': userId,
    'avatarActive': "$activeAvatar",
    'data': await MultipartFile.fromFile(file.path),
  });
  var response = await dio.post('https://gamification.ird.global/api/uploadavatar', data: formData);

  if (response.statusCode == 200) {
    // print(await response.stream.bytesToString());
    responseModel = responseStatusModelFromJson(response.toString());
    print("avatar upload response ${responseModel.status}");

    return responseModel;
  } else {
    print("else response from avatar upload $response.statusMessage");
    return null;
  }
} on Exception catch (e) {
  print('catch error from avatar upload API $e');
  return null;
}

}

Sign up to request clarification or add additional context in comments.

3 Comments

thank you! but for me sending the file is ok, the issue is send an entire json object using multipartrequest!
I've updated my answer check and let me know if it's work
using dio and formData helps sending the json object, but the type sent is an octet-stream and the server that I'm sending data to is made using spring and it does not support octet-stream type! do you have a solution for this issue? thanks for the time btw
1

FLUTTER HTTP

Flutter multipart request fields take only Map<String, String>. If you pass Map<String, dynamic> will arise error.

You need to encode your Map<String,dynamic> then covert to string.

if your server can decode this string you can apply my solution

THE SOLUTION FOR ME:

var data = {
      "State":"test",
      "City":"test",
      "Street": "test",
      "location":{
                "lat":1.2,
                "lang":2.1
      }
};

var header = {
  "Content-Type": 'multipart/form-data',
  "Accept": 'application/json'
};



Map<String, String> obj = {"barberAddress": json.encode(data).toString()};
var request = http.MultipartRequest("POST", Uri.parse("url here"))
  ..fields.addAll(obj)
  ..headers.addAll(header)
  ..files.addAll(files);

var streamResponse = await request.send();
var response = await http.Response.fromStream(streamResponse);
// Your result here

IN SEVER SIDE

LARAVEL:

$obj = json_decode($request["barberAddress"], true);
// Your code here

OR

$obj = json_decode($request->barberAddress, true);
// Your code here

IF IT IS HARD TO DECODE YOUR OBJECT ON SEVER USE

flutter dio package through this link : dio flutter package

I THINK MAY HELP SOMEONE

Comments

0

The solution to this problem is dealing with the json as a file instead of a field.Instead of using the "request.fields" method you should use the "request.files" method after generating a json file. As well as you do with the MultipartFile. This avoid to get a error from the API for a Content-Type: application/octet-stream So your code would look something like this:

Future syncLocalDataToMobileSig(
      {required EntrepriseAgricultureCharegement
          entrepriseAgricultureCharegement}) async {
    Uri uri = Uri.parse("$baseUrlMobile/new");

    var request = http.MultipartRequest("POST", uri);
    request.headers.addAll({"Content-Type": "multipart/form-data"});
    File file = File(
        "/data/user/0/com.example.app_amee/app_flutter/IMG_20220115_113910.jpg");
    var stream = http.ByteStream(file.openRead());
    stream.cast();
    var length = await file.length();
    var multipartFile = http.MultipartFile(
      "files",
      stream,
      length,
    );
   request.files.add(multipartFile);

   final jsonData = jsonEncode(entrepriseAgricultureCharegement.toJson());
   final jsonPart = http.MultipartFile.fromString(
    "objectField",
    jsonData,
    filename: 'data.json',
    contentType: MediaType('application', 'json'),
  );
    request.files.add(jsonPart);


    try {
    var streamedResponse = await request.send();
    final responseData = await streamedResponse.stream.toBytes();
    final responseString = String.fromCharCodes(responseData);
    print(responseString);
    } catch (e) {
      print("e => $e");
    }
  }

Comments

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.