beyondraymond
beyondraymond

Reputation: 11

Android Download Manager downloads corrupted file / cannot open file after downloading / retrofit authentication token used in download mana

I'm trying to download a file from the server and after it finished downloading, the downloaded file is not recognized by the phone. I did set the mime type from the file extension of the downloaded file and the server uses a bearer token which is why I passed the token as a header but the file is still corrupted. By the way, I use retrofit to fetch the bearer token after login. The api was created using laravel. My hypothesis is that download manager is not permitted to download the file since it is not authenticated and the token that I fetched only applies to the retrofit requests of the app. Sorry for my bad english, anyway here's my download request.

val downloadBaseUrl = "https://ticaphub.com/event-files/"
val urlRequest = downloadBaseUrl + filepath
val request = DownloadManager.Request(Uri.parse(urlRequest))
val downloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val title = URLUtil.guessFileName(urlRequest, null, null)
val cookie = CookieManager.getInstance().getCookie(urlRequest)

    request.setTitle(title)
    request.setDescription("Downloading File Attachments.")
    request.addRequestHeader("Authorization", "Token " + this@TaskDetailsActivity
        .getSharedPreferences("loginCredential", Context.MODE_PRIVATE)
        .getString("userToken", "0"))
    request.addRequestHeader("cookie", cookie)
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, clickedItem.name)
    request.setMimeType(getMimeFromFileName(urlRequest))
    downloadManager.enqueue(request)

//The function I use to get the MIME type of the file

    private fun getMimeFromFileName(url: String): String {
    return URLConnection.guessContentTypeFromName(url)
}

Upvotes: 1

Views: 970

Answers (0)

Related Questions