fun downloadFile(url: String) {
Glide.with(this).asFile().load(url).listener(object : RequestListener<File?> {
override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<File?>?, isFirstResource: Boolean): Boolean {
return false
}
override fun onResourceReady(resource: File?, model: Any?, target: Target<File?>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
saveFile(this@FlowActivity, resource, "image")
return false
}
}).submit()
}
fun saveFile(context: Context, file: File?, mimeType: String): Uri? {
var folderName = "Pictures"
var extension = ".jpg"
when (mimeType) {
"gif" -> {
extension = ".gif"
}
"image" -> {
extension = ".jpg"
}
"video" -> {
extension = ".mp4"
folderName = "Movies"
}
"audio" -> {
extension = ".mp3"
folderName = "Music"
}
"pdf" -> {
extension = ".pdf"
folderName = "Documents"
}
}
if (Build.VERSION.SDK_INT >= 29) {
val values = ContentValues()
values.put(MediaStore.Files.FileColumns.MIME_TYPE, mimeType)
values.put(MediaStore.Files.FileColumns.DATE_ADDED, System.currentTimeMillis() / 1000)
values.put(MediaStore.Files.FileColumns.DATE_TAKEN, System.currentTimeMillis())
values.put(MediaStore.Files.FileColumns.RELATIVE_PATH, folderName)
values.put(MediaStore.Files.FileColumns.IS_PENDING, true)
values.put(MediaStore.Files.FileColumns.DISPLAY_NAME, "file_" + System.currentTimeMillis() + extension)
var uri: Uri? = null
when {
mimeType.contains("image") -> {
uri = context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
}
mimeType.contains("video") -> {
uri = context.contentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values)
}
mimeType.contains("audio") -> {
uri = context.contentResolver.insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values)
}
mimeType.contains("pdf") -> {
uri = context.contentResolver.insert(MediaStore.Files.getContentUri("external"), values)
}
}
uri?.apply {
runCatching {
saveFileToStream(contentResolver.openInputStream(Uri.fromFile(file))!!, contentResolver.openOutputStream(uri)!!)
values.put(MediaStore.Video.Media.IS_PENDING, false)
context.contentResolver.update(this, values, null, null)
return this
}.getOrElse {
return null
}
}
}
return null
}
private fun saveFileToStream(input: InputStream, outputStream: OutputStream) {
input.use { input ->
runCatching {
outputStream.use { output ->
val buffer = ByteArray(4 * 1024) // or other buffer size
var read: Int
while (input.read(buffer).also { read = it } != -1) {
output.write(buffer, 0, read)
}
output.flush()
}
}
}
}
|