3

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.

0

2 Answers 2

7

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

1 Comment

This is a fantastic solution, but I am having a minor issue. I was trying to send a list and it was getting converted to a string. Lists must be uploaded as files.... stackoverflow.com/questions/60791168/…. I was originally using DIO, but it is unreliable.
1

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.

3 Comments

could you please share additional information regarding the same, how can I solve my issue
Sure, I was using mobile when I wrote this answer, I am updating it.
,Thanks friend, for the time bieng I used dio package with formdata. I will try your suggested method also ,It would be a new learning to me.

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.