DKumar

In most of applications, There is need to upload photos/videos. It is easy to open camera and gallery via intent but developers face issues when they start to test this functionality on different Android OS versions. For example:
1. Need to declare storage permissions and handle them based on OS versions
2. Below marshmallow, Only declare permissions in manifest and system auto grant these permissions
3. From marshmallow, We need to handle runtime permissions which are declared in manifest
4. From android 10 and above, There is limitation with external storage(Scope storage)

So keep in mind, I am writing here every case which works on every OS version. I’ll break this explanation in three parts:
1. Capture photo via intent
2. Capture video via intent
3. Pick photo/video via intent
4. Upload media to server using Retrofit

--

--

In my previous articles, I explained capture photo, capture video and pick media and show bitmap and save it in scope storage.
Now it’s time to upload captured or picked media to server. I am assuming you have done your Retrofit setup. If not then check here to setup Retrofit.
To upload media, Retrofit uses multipart:
1. Declare api function:

@Multipart
@POST(URL_UPLOAD_MEDIA)
suspend fun uploadMediaApi(@Part fileAsMultipartBody: MultipartBody.Part): Response<YourServerResponsePojo>

2. Upload media file using above function:

fun uploadImage(file: File, mimeType: String) {
viewModelScope.launch {
withContext(Dispatchers.IO){
val part = MultipartBody.Part.createFormData(
"keyNameServerExpect", file.name, RequestBody.create(
MediaType.parse(mimeType),
file
)
)
//use retrofit instance to call api
val response = retrofitBuilder.getApiInterface().uploadMediaApi(part)
}
}
}
}

--

--