1、传单独的文件service如下:
@Multipart @POST Observable<CommonBean> uploadFileService( @Url String url, @Part MultipartBody.Part fileInfo );
2、传单独的数组文件service如下:
@Multipart @POST Observable<CommonBean> uploadFilesService( @Url String url, @Part MultipartBody.Part[] fileInfos );
3、传文件以及参数的service如下:
@Multipart @POST Observable<CommonBean> uploadUserInfo( @Url String url, @PartMap Map<String, RequestBody> params, @Part MultipartBody.Part[] files, @Part MultipartBody.Part file );
接口定义完成后再构建一下参数即可: 例如:
//普通参数
HashMap<String, RequestBody> map = new HashMap<>(); map.put("userId", toRequestBody(userId+"")); //文件数组 MultipartBody.Part filePart[] = new MultipartBody.Part[2]; RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), files[0]); filePart[0] = MultipartBody.Part.createFormData("file", files[0].getName(), requestFile); RequestBody requestFile1 = RequestBody.create(MediaType.parse("multipart/form-data"), files[1]); filePart[1] = MultipartBody.Part.createFormData("file", files[1].getName(), requestFile1); //单个文件 RequestBody requestFilep = RequestBody.create(MediaType.parse("multipart/form-data"), fileSingle); MultipartBody.Part filePartuserp = MultipartBody.Part.createFormData("fileSingle", fileSingle.getName(), requestFilep);
//toRequestBody方法
private RequestBody toRequestBody(String value) { RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), value); return requestBody; }
//最后发送请求 这块使用到了Rxjava
service.uploadParamAndFiles(Constants.URL, map,filePart,filePartuserp) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(observer);