使用OkHttp上传多张图片

使用OkHttp上传多张图片

OkHttpClient okHttpClient = new OkHttpClient();
MultipartBody.Builder builder = new MultipartBody.Bui
OkHttpClient okHttpClient = new OkHttpClient();
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
//mHashMap是图片path的集合
if(mHashMap !=null&&selectList!=null){
    for (int i = 0; i < selectList.size(); i++) {
        File f = new File(mHashMap.get(i));
        if (f == null) break;
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            Bitmap bm = BitmapFactory.decodeFile(f.getAbsolutePath(), options);
            bm.compress(Bitmap.CompressFormat.JPEG, 90, new FileOutputStream(f));
            bm.recycle();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        builder.addFormDataPart("img[]", f.getName(), RequestBody.create(MEDIA_TYPE_PNG, f));
    }
}
builder.addFormDataPart("type",committype);
builder.addFormDataPart("id",spotid);
builder.addFormDataPart("cont",txt.getText().toString());
builder.addFormDataPart("userid","2");
MultipartBody requesBody = builder.build();
RequestBody body = new FormBody.Builder()//这里跟后台协商的接口有关
        .add("type", "sd")
        .add("id", spotid)
        .add("cont", txt.getText().toString())
        .add("userid", "2")
        .build();
Request request = new Request.Builder().url(Url.PostCommitUrl).post(requesBody).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
    
}

你可能感兴趣的:(使用OkHttp上传多张图片)