Anoop
Anoop

Reputation: 146

How to send json object with http post multipart request in Flutter

I have to send a multipart HTTP post request that contains a image, body and header, Please find the body format

 body: {
        "Id":Id,
        "Details": {
          "name": Name,
          "centroid": centroid,
          "attribute": {
            "boundaryOpacity": boundaryOpacity,
            "boundaryWeight": boundaryWeight,
            "boundaryColor": boundaryColor,
            "labelColor": labelColor,
          },
},}
 headers: {
        'tenantId': tenantId,
        'Content-Type': 'multipart/form-data',
        'x-access-token': token
      },

I have to send image along with this request .Please help me with this.

Upvotes: 2

Views: 8065

Answers (2)

You can convert your map into multipartRequest and set your headers in multipartRequest.

Future<void> addProject(Project project, [File? file]) async {
    final url = Uri.parse('$baseUrl/api/projects');

    final format = DateFormat('yyyy-MM-dd');
    final completionDate = format.format(project.completionDate);
    final data = {
      'id': project.id,
      'title': project.title,
      'description': project.description,
      'image': project.image,
      'completion_date': completionDate,
    };

    try {
      var request = http.MultipartRequest('POST', url);
      request = jsonToFormData(request, data);
      request.headers['X-Requested-With'] = "XMLHttpRequest";
      request.headers['Authorization'] = "Bearer $authToken";

      if (file != null) {
        request.files
            .add(await http.MultipartFile.fromPath("image", file.path));
      }
      final response = await request.send();
      final responseData = await response.stream.toBytes();
      final responseString = String.fromCharCodes(responseData);
      print(responseString)
      notifyListeners();
    } catch (error) {
      print('Error add project $error');
      throw (error);
    }    
}
jsonToFormData(http.MultipartRequest request, Map<String, dynamic> data) {
    for (var key in data.keys) {
      request.fields[key] = data[key].toString();
    }
    return request;
}

Upvotes: 5

Ravindra
Ravindra

Reputation: 152

You can't send json encoded string with multipart, you have to do it formdata way, you may need to update your backend code

final req = http.MultipartRequest('POST', url);
// Write your add files statement here
req.fields['id'] = id; // This is your id field
req.fields['details[name]'] = Name; // This is name field in details object
req.fields['details[attribute][boundaryOpacity]'] = boundaryOpacity; // This is how you write nested fields

You can follow same pattern for other fields as well, you need to implment a check for null field, assuming id can be null, write it as follows

req.fields['id'] = id != null ? id : ''; // If it is null convert it to empty string or don't include it

Alternate solution

Add a data field and convert entire payload to json string and decode at backend.

Upvotes: 1

Related Questions