参考如下方式
@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
有兴趣的可以直接阅读原文,我这里只是捡重点