Welcome to OGeek Q&A 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...