您的位置:首页 > 其它

Retrofit 上传多张图片/文件

2016-06-22 14:41 507 查看
不多说,直接上代码,感兴趣的话可以自己去看看 retrofit

接口中的方法

public interface WebApiServices {

String baseUrl = ""; // baseUrl
@Multipart
@POST("/xxx/xxx/xxx/xxx/") //这里是Url
Call<Ret> submitUserInfoChange(@PartMap Map<String, RequestBody> infoWidthPhoto);

}


public class RetrofitManager {

private static Retrofit retrofit = null;
private static OkHttpClient client = new OkHttpClient()
.newBuilder().connectTimeout(60, TimeUnit.SECONDS).build();

public static WebApiServices getWebApiService() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(WebApiServices.BASEURL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
}
return retrofit.create(WebApiServices.class);
}
}


调用方式

private RequestBody transformationParams(String param) {
String content = TextUtils.isEmpty(param) ? "" : param;
return RequestBody.create(MediaType.parse("text/plain"), content);
}

//提交数据
private void submitData(SubmitPostBena mBean, List<String> faile) {
if (SystemUtils.checkNet(this)) {
WebApiServices webApiService = RetrofitManager.getWebApiService();
Map<String, RequestBody> post = new HashMap<>();
post.put("tagIds", transformationParams(mBean.getTagIds()));
List<String> imagePaths = mBean.getImagePaths();
int pathCount = imagePaths.size();
for (int i = 0; i < pathCount; i++) {
File file = new File(imagePaths.get(i));
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
post.put("img" + i + "\"; filename=\"" + file.getName(), requestFile);
}
}
Call<Ret> call = webApiService.submitPost(post);
call.enqueue(new Callback<Ret>() {
@Override
public void onResponse(Call<Ret> call, Response<Ret> response) {
if (response.isSuccessful()) {
Ret body = response.body();
if (body.getRet().equals("1")) {

} else {

}
}
}

@Override
public void onFailure(Call<Ret> call, Throwable t) {
LogUtil.e(TAG, t);
}
});
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息