Skip to content

Instantly share code, notes, and snippets.

@raystatic
Created March 2, 2022 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raystatic/62c647afae64c1424fb28ce744647a2e to your computer and use it in GitHub Desktop.
Save raystatic/62c647afae64c1424fb28ce744647a2e to your computer and use it in GitHub Desktop.
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