2017-03-07 24 views
0

要求將圖像連同純文本和明文數據一起上傳整數列表。 我使用@PartMap爲純數據改造 - 將Integer數組列表與圖像文件相結合

對於這裏的圖像部分是我的代碼

imageFile = new File(imagePath); 
imageBody = RequestBody.create(MediaType.parse("image/*"), imageFile); 
multipartImageBody = MultipartBody.Part.createFormData("file_name", imageFile.getName(), imageBody); 

對於純數據

userIdBody = RequestBody.create(MediaType.parse("text/plain"), userId); 
customerTypeBody = RequestBody.create(MediaType.parse("text/plain"), typeOfCustomer); 

結合明文數據

HashMap<String, RequestBody> partMap = new HashMap<>(); 
partMap.put("userId", userIdBody); 
partMap.put("customer_type", customerTypeBody); 

請求

發生
@POST<T> methodName(@PartMap Map<String, RequestBody> params, @Part MultipartBody.Part imageParam); 

問題,如果我嘗試添加整數listarray爲Requestbody,將數據轉換成服務器無法解析,而我們應該從應用程序方面本身

我試圖

RequestBody.create(Mediatype,byte[]) 
發送正確的數據串

Requestbody有這種方法,它接受我們的數據作爲字節數組,我將數組轉換爲字節數組,但結果並不如預期。

我還有其他的可能嗎?

+0

可以使用multipart上傳帶有文本數據的圖像 – Sony

+0

我實際上有多個文本數據 –

回答

0

使用這樣的接口部分

@Multipart 
@POST("your/link") 
Call<SuccessMessage> yourMethod(@Part MultipartBody.Part image, 
                  @Part MultipartBody.Part[] data);//here you can use partmap also 

,這裏是如何使用它

MultipartBody.Part img = RequestHelper.multiPartBobyPart(image, "image"); 


    MultipartBody.Part[] parts = new MultipartBody.Part[size]; 
     for (int i = 0; i < size; i++) { 
      parts[i] = RequestHelper.multiPartBobyPart(yourStringArrayList.get(i), "var[]"); 
     } 
    Call<SuccessMessage> call = mNetworkInterface.applyForDomesticJob(img, parts); 
    call.enqueue(this); 

這裏是請求輔助類

public final class RequestHelper { 

public static MultipartBody.Part multiPartBobyPart(java.io.File file, String parameterName) { 
    return MultipartBody.Part.createFormData(parameterName, file == null ? "noFile" : file.getName(), 
      RequestBody.create(MediaType.parse("multipart/form-data"), file == null ? new java.io.File("") : file)); 
} 

public static RequestBody getRequestBody(String parameter) { 
    return RequestBody.create(MediaType.parse("multipart/form-data"), parameter); 
} 


public static MultipartBody.Part multiPartBobyPart(String data, String parameterName) { 
    return MultipartBody.Part.createFormData(parameterName, data); 
} 

}

我們e this link有關更多詳細信息

+0

它適用於普通字符串數據,但不適用於int arraylist。 –

+0

你想發送一個整數數組嗎? – Sony

+0

是的,我在問題中提到過它。 –

0

int[]轉換爲byte[]聽起來像是存在問題。您應該檢查服務器接受數據的端點,並查看您的轉換代碼是否使用相同的字節序。您可以使用ByteBuffer進行轉換,它具有order()方法來指定endianess。

我沒有任何問題改造的 RequestBody.create我自己,所以我懷疑這是這裏的問題。