Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

How to send json object in 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.

question from:https://stackoverflow.com/questions/65623460/how-to-send-json-object-in-http-post-multipart-request-in-flutter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...