Retrofit 檔案(圖片)和引數同時上傳的方法
阿新 • • 發佈:2019-01-30
參考如下方式
@Multipart
@POST(NRConfig.UPDATE_FILES)
Call<Result<UpdateFilesEntity>> updateOneFile(@PartMap Map<String,RequestBody> data,@Part("pic") RequestBody description,@Part MultipartBody.Part file);
使用@Multipart註解,引數通過@PartMap形式上傳,注意,這裡一定要用Map<String,RequestBody>這樣的格式,
也只能用RequestBody形式,本身retrofit是僅支援兩種形式的String型別,這裡的不在其中,故此不支援直接使用
String型別,必須轉成RequestBody形式,附上轉型方法
public static RequestBody toRequestBody(String value) {
RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), value);
return requestBody;
}
如果執意要用其他型別傳,基本上會在後臺得到的資料中出現多出來的一對雙引號!
最後再給上完整的程式碼
/** * @param callback * @return */ public static Call updateOneFile(Map<String,RequestBody> type, File file, final ResultCallback<Result<UpdateFilesEntity>> callback) { if (callback == null) throw new NullPointerException("callback == null"); NRService mService = ServiceFactory.createNewService(NRService.class); RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file); MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), reqFile); String descriptionString = "image"; RequestBody description = RequestBody.create(MediaType.parse("multipart/form-data"), descriptionString); Call<Result<UpdateFilesEntity>> call = mService.updateOneFile(type, description, body); Callback<Result<UpdateFilesEntity>> cbk = new Callback<Result<UpdateFilesEntity>>() { @Override public void onResponse(Call<Result<UpdateFilesEntity>> call, Response<Result<UpdateFilesEntity>> response) { Result.onResponse(response, callback); } @Override public void onFailure(Call<Result<UpdateFilesEntity>> call, Throwable t) { Result.onFailure(t, callback); } }; call.enqueue(cbk); return call; }
參考地址:http://blog.csdn.net/honghailiang888/article/details/62884231
有興趣的可以直接閱讀原文,我這裡只是撿重點