Faisal Khalid
Faisal Khalid

Reputation: 650

Downloading file and saving it to download folder using kotlin in Android

I am trying to download an apk file from the web server and store it in the download folder. I am using fuel library

Fuel.download("https://mypath/app.apk").destination { 
    response, url -> val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()) File(dir, "abcd.apk")    
}.progress {
    readBytes, totalBytes -> val progress = readBytes.toFloat() / totalBytes.toFloat()
    Log.d("log",progress.toString())
}.response {
    req, res, result -> Log.d("log","download completed ")    
    Log.d("log",Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/abcd.apk")
}

I am getting bytesArray in response but the file is not saving to download folder. I have write_external_storage on my Manifest file. Please let me know what am I missing?

Upvotes: 2

Views: 9136

Answers (2)

Sagar Maheta
Sagar Maheta

Reputation: 1

fun storeImage(link: String) : String {
    val policy: StrictMode.ThreadPolicy = StrictMode.ThreadPolicy.Builder().permitAll().build()
    StrictMode.setThreadPolicy(policy)
    val cw = ContextWrapper(applicationContext)
    val directory: File = cw.getDir("imageDir", Context.MODE_PRIVATE)
    val pictureFile = File(directory, "backgroundImage.gif")
    URL(link).openStream().use { input ->
        FileOutputStream(pictureFile).use { output ->
            input.copyTo(output)
            Log.e("DD GIF", "storeImage: FILE SAVED" )
            return "SAVED"
        }
    }
}

it is working for me.

Upvotes: 0

Sachin Chandil
Sachin Chandil

Reputation: 17809

As you mentioned in comment that you are using targetSdkVersion as 23. Beginning with Android 6.0 (API level 23), if you set targetSdkVersion as 23 in your app you have to implement rumtime permission in your app.

To implement it please refer official documentation here Requesting Permissions at Run Time

Upvotes: 2

Related Questions