Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
private fun getSavedFileUri(
fileName:String,
fileType:String,
fileUrl:String,
context: Context): Uri?{
val mimeType = when(fileType){
"PDF" -> "application/pdf"
"PNG" -> "image/png"
"MP4" -> "video/mp4"
else -> ""
} // different types of files will have different mime type
if (mimeType.isEmpty()) return null
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
put(MediaStore.MediaColumns.MIME_TYPE, mimeType)
put(MediaStore.MediaColumns.RELATIVE_PATH, "Download/DownloaderDemo")
}
val resolver = context.contentResolver
val uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues)
return if (uri!=null){
URL(fileUrl).openStream().use { input->
resolver.openOutputStream(uri).use { output->
input.copyTo(output!!, DEFAULT_BUFFER_SIZE)
}
}
uri
}else{
null
}
}else{
val target = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
fileName
)
URL(fileUrl).openStream().use { input->
FileOutputStream(target).use { output ->
input.copyTo(output)
}
}
return target.toUri()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment