fun saveImage(url: String, file: File) { val client = OkHttpClient() val request= Request.Builder().url(url).build() client.newCall(request).execute().use { response -> if (!response.isSuccessful) throw IOException("Unexpected code $response") for ((name, value) in response.headers) { // Timber.d("$name: $value") } val source = response.body!!.source() val sink = file.sink().buffer() source.use { input -> sink.use { output -> output.writeAll(input) } } }}coroutineScope.launch(Dispatchers.IO) { val file = File.createTempFile( "${context.getString(R.string.app_name)}_", ".png", Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOWNLOADS ) ) saveImage(blobUrl, file) withContext(Dispatchers.Main) { // showToast("File saved") }}
References: