How to download a file using file name

73 Views Asked by At

I have a list of records which I am getting from the API call, on the each item of that list I have a file name with other data. That file name is something like f354jklja.png or kioad87943kjkjd.pdf. I am using that list on the recyclerview, in the each recyclerview item I have a icon , what I want to do is on the click of that icon corresponding file will be download on the phone storage. How can I do that I am not getting any proper idea. Can anyone please help me to solve this?

override fun showPrecription(record: Record) {
        if (record.file!=null){
            val context: Context = this

            // Check if the app has the WRITE_EXTERNAL_STORAGE permission
            if (ContextCompat.checkSelfPermission(
                    context,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                // Request the permission
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                    REQUEST_WRITE_EXTERNAL_STORAGE_PERMISSION
                )
                fileNameToDownload=record.file
            } else{
                downloadFile(Helper.RECORDS_URL,record.file)
            }
        }else Toast.makeText(this,"File path is not exist",Toast.LENGTH_LONG).show()
        // Get the base context

    }

This is the function what will trigger on the click of the recyclerview item:

    fun downloadFile(fileUrl: String, fileName: String) {
        val request = DownloadManager.Request(Uri.parse(fileUrl))
            .setTitle(fileName)
            .setDescription("Downloading")
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName)

        val downloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
        downloadManager.enqueue(request)
    }
downloadFile function .

Using this code the file is not downloading in my phone storage.

0

There are 0 best solutions below