接口声明如下所示
@Multipart
@POST(Api.API_UPLOAD_IMAGE)
Call<ResponseBody> uploadImage(@Query("flag") String flag,@Part MultipartBody.Part image);
图片需要转换成对应的MultipartBody.Part类型
File file = new File(path);
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(path);
if (extension != null) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
RequestBody requestBody = RequestBody.create(MediaType.parse(type), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestBody);
发起网络请求
Call<ResponseBody> call = client.uploadImage("one", body);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
uploadImageSucceed();
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable throwable) {
uploadImageFailed();
}
});