Search code examples
androidokhttpandroid-10.0scoped-storage

How I can upload photos by Uri instead of File in Android Q using okhttp


I'm using Okhttp (com.squareup.okhttp3:okhttp:3.12.10) to upload photos to the server using this code

MultipartBody.Builder builder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("imageType", Img_tag)
                    .addFormDataPart("created", Calendar.getInstance().getTime() + "")
                    .addFormDataPart("comment", comment + ""))

            for (int i = 0; i < IMG_PATHs.size(); count = ++i) {
                String IMG_Name = IMG_PATHs.get(i).substring(IMG_PATHs.get(i).lastIndexOf("/") + 1);
                String IMG_Extention = IMG_Name.substring((IMG_Name.lastIndexOf(".") + 1));

                builder.addFormDataPart("imageFile" + i, IMG_Name,
                        RequestBody.create(MEDIA_TYPE, new File(IMG_PATHs.get(i))))
                        .addFormDataPart("ext" + i, IMG_Extention);
            }
            builder.addFormDataPart("count", count + "");
            MultipartBody requestBody = builder.build();
            Request request = new Request.Builder()
                    .url(PTHOT_UPLOAD_PATH)
                    .post(requestBody)
                    .build();

Now after I update to scoped storage in the android Q I have a list of Uri, what should I change to this request to upload the photos?


Solution

  • That was solved after issuing a comment: InputStreamRequestBody.

    https://github.com/square/okhttp/issues/3585#issuecomment-327319196