天天看點

Retrofit 上傳多張圖檔/檔案

不多說,直接上代碼,感興趣的話可以自己去看看 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(, 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 = ; 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);
                }
            });
        }
    }
           

繼續閱讀