Reputation: 41
Data in JSON format I need to pass is:
{
"user":{
"email":"xxxx",
"password":"xxxx",
"first_name":"XXXX",
"last_name":"XXXX",
"date_of_birth":"XXXX",
"image":"myFile.jpg",
"location":"XXXX",
"my_list1":[
{
"first_name":"XXXX",
"last_name":"XXXX",
"telephone_number":"XXXX"
},
{
"first_name":"XXXX",
"last_name":"XXXX",
"telephone_number":"XXXX"
}
],
"my_list2":[
{
"id":"1"
},
{
"id":"2"
}
]
}
}
I can not add an image in mainRequestObj while using:
@POST("users")
Call<MainResponse> register(@Header("abc") String abc,@Body MainRequestObj mainRequestObj);
Is there any way I can pass the image as a file in the raw body format? I am using retrofit 2.9.0. Thanks in advance!
Upvotes: 1
Views: 1043
Reputation: 61
You can convert your bitmap into a base64 string and send it to the server.
But you should send the multipart request. As I read your comment there is a list of objects that you want to send to the server. You should create a POJO that contains your list of data and then send it along with the multipart request.
Here is some code example:
class SyncUpData {
@SerializedName("Products")
var products: List<ProductDTO>? = null
@SerializedName("ProductTax")
var productTax: List<ProductTaxDTO>? = null
}
And along with your multipart request do like this:
val str = GsonBuilder().create().toJson(syncUpObj)
val jsonObject: JSONObject = JSONObject(str)
val body = jsonObject.toString(1)
val syncUp = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), body)
Your API Call:
@Multipart
@POST("")
Call<ResponseDTO> syncUpNow(@Part MultipartBody.Part[] images,
@Part("syncUp") RequestBody myObj
Upvotes: 1
Reputation: 931
You have to use form data for your POST
API then you can achieve this. you have to get some help from your back-end developer as well. check this below example code. Try this way and let me know your finding
@Multipart
@POST("expenses/upload")
Observable<UploadExpensesWithImageResponse> uploadExpensesWithImageAPI(
@Header("Authorization") String accessToken,
@Part MultipartBody.Part[] picture,
@Part("store_id") RequestBody store_id,
@Part("amount") RequestBody amount,
@Part("expense_date") RequestBody expense_date);
Upvotes: 0