标签:
普通写法:
//创建表单的普通字段
public static RequestBody createFormBody(String content) { RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), content); return body; }
//创建Multipart, fieldName为表单字段名 public static MultipartBody.Part createFilePart(String fieldName, File file) { RequestBody requestFile = RequestBody.create(MediaType.parse("application/otcet-stream"), file); MultipartBody.Part body = MultipartBody.Part.createFormData(fieldName, file.getName(), requestFile); return body; }
//Service方法, 普通form表单使用RequestBody, 并且@Part注解要写表单字段名 //文件用MultipartBody.Part @Multipart @POST(API.VIDEO_MODULE_UPLOAD_VIDEO) Call<Object> uploadImage(@Part MultipartBody.Part imagePicFile, @Part MultipartBody.Part videoFile, @Part("videoDescription") RequestBody desc, @Part("videoPicWidth") RequestBody videoPicWidth, @Part("videoPicHeight") RequestBody videoPicHeight);
//上传 getService(VideoService.class).uploadVideo( createFilePart("videoPicFile",new File(mCoverPath)), createFilePart("videoFile",new File(mPath)), createFormBody(etVideoDesc.getText().toString().trim()), createFormBody(width), createFormBody(height)) .enqueue(new JsonResultCallback<Object>(context()) { @Override public void onSuccess(Call<Object> call, Object data) { super.onSuccess(call, data); //..... } @Override public void onFinish(Call<Object> call) { //... } });
注意: 如果你使用了 GsonRequestBodyConverter 或类似的RequestBodyConverter, 一定记得要略过@Multipart 标注的Service方法, 否则你的File会被转为文件路径的字符串, 这是一个坑
另一种, 自定义FileRequestBodyConverter:
未完待续...
相关链接, 这里有实现
标签:
原文地址:http://www.cnblogs.com/duwei/p/retrofit2_upload_image_file.html