Ability to download attachments
Closed this issue · 1 comments
bosukas commented
Summary
Currently there is no way to download attachments without creating your own function for it, however I feel like it would be a nice extension function with kord-extensions.
Preferred Behaviour
Maybe an extension function for attachments could be added, something like:
attachment.downloadToFile(fileUrl)
attachment.downloadToPath(pathUrl)
Suggestions
I have an extension function for the http client that lets you download from URLs. I don't know if its the best approach but it works.
suspend fun HttpClient.downloadToFile(file: File, url: String) {
// create file if it does not exist
if(!file.exists()) {
withContext(Dispatchers.IO) {
file.createNewFile()
}
}
// check if we can write to the file
require(file.canWrite()) { "Cannot write to file '${file.name}'"}
val bytes = get<ByteReadChannel>(url)
val bufferSize = 1024*100
val buffer = ByteArray(bufferSize)
// download the content at the url and write that content to the file
withContext(Dispatchers.IO) {
FileOutputStream(file).use {
do {
val currentRead = bytes.readAvailable(buffer)
// channel has closed
if(currentRead == -1) {
break
}
it.write(buffer, 0, currentRead)
} while (currentRead >= 0)
}
}
}
gdude2002 commented
Done, see the utils docs for info after they build.