一 定义上传图片的接口
@Multipart
@POST("fileUpload.zy")
Call uploadImage(@Part() MultipartBody.Part file);//单张图片上传
@Multipart
@POST("fileUpload.zy")
Call uploadManyImage(@Part() MultipartBody.Part [] file);//多张图片上传
}
二、单张图片上传
1、创建RequestBody
File file = new File(path);
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
2、创建MultipartBody.Part,其中需要注意第一个参数需要与服务器对应
MultipartBody.Part part = MultipartBody.Part.createFormData("myfiles", file.getName(), requestFile);
3、调用uploadImage上传图片
IUserBiz iUserBiz =retrofit.create(IUserBiz.class);
Call call = iUserBiz.uploadImage(part);
call.enqueue(callback);
三,多张图片上传
比如需要同时上传三张图片
首先创建3个RequestBody;
File file1= new File(path1);
File file2= new File(path2);
File file3= new File(path3);
RequestBody requestFile1 =
RequestBody.create(MediaType.parse("multipart/form-data"), file1);
RequestBody requestFile2 =
RequestBody.create(MediaType.parse("multipart/form-data"), file2);
RequestBody requestFile3 =
RequestBody.create(MediaType.parse("multipart/form-data"), file3);
2、创建MultipartBody.Part的数组
MultipartBody.Part [] part =newMultipartBody.Part[3];
下面第一个参数还是与服务器的对应
part[0] =MultipartBody.Part.createFormData("myfiles", file1.getName(), requestFile1);
part[1] =MultipartBody.Part.createFormData("myfiles", file2.getName(), requestFile2);
part[2] =MultipartBody.Part.createFormData("myfiles", file3.getName(), requestFile3);
3、调用uploadManyImage上传图片
IUserBiz iUserBiz =retrofit.create(IUserBiz.class);
Callcall = iUserBiz.uploadManyImage(part);
call.enqueue(callback);