1.单文件上传
//图片的单独的上传 (接口定义) @Multipart @POST("common/uploadPhoto") Call<ResponseBody> psot_send_singlepic(@Part MultipartBody.Part file);
(方法) private void send_picture_cover(String compress_path) {
Retrofit retrofit = new Retrofit.Builder().baseUrl(UrlTools.BASE_URLIMG)//图片上传在这里 要切换地址.addConverterFactory(GsonConverterFactory.create()).build(); Api repo = retrofit.create(Api.class); //拿到文件流 File file = new File(compress_path);//定义类型 RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file); //参数名称 为 file MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);Call<ResponseBody> call_sendpic = repo.psot_send_singlepic(body);}
2. 多文件上传
(1)接口定义
@Multipart@POST("common/uploadOssFiles")Call<ResponseBody> psot_batch(@Header("app-token-req") String header, @Part() List<MultipartBody.Part> parts);
(2)接口调用
private void send_picture(List<File> file_list) {
Retrofit retrofit = new Retrofit.Builder().baseUrl(UrlTools.BASE_URLIMG)//图片上传在这里 要切换地址.addConverterFactory(GsonConverterFactory.create()).build();Api repo = retrofit.create(Api.class);List<MultipartBody.Part> parts = new ArrayList<>();//必须要保证后台 也是集合接收for (int i = 0; i < file_list.size(); i++) {RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file_list.get(i));MultipartBody.Part part = MultipartBody.Part.createFormData("files", file_list.get(i).getName(), requestBody);//这里的files 是后台接受集合时的参数parts.add(part); }Call<ResponseBody> call_sendpic = repo.psot_batch(UserData.getUserToken(this), parts);
}