Android

Webview 파일 다운로드

Wook No.1 2022. 12. 26. 18:05

Webview에서 이미지나 파일을 다운로드 하려고 할때 Webview setDownloadListener를 사용하면 된다.

 

Webview.setDownloadListener { url, userAgent, contentDisposition, mimeType, contentLength ->
    try {
        val request = DownloadManager.Request(Uri.parse(url))
        val dm = getSystemService(DOWNLOAD_SERVICE) as DownloadManager

        var fileName = contentDisposition
        if (!fileName.isNullOrBlank()) {
            val idxFileName: Int = fileName.indexOf("filename=")
            if (idxFileName > -1) {
                fileName = fileName.substring(idxFileName + 9).trim()
            }
            if (fileName.endsWith(";")) {
                fileName = fileName.substring(0, fileName.length - 1)
            }
            if (fileName.startsWith("\"") && fileName.endsWith("\"")) {
                fileName = fileName.substring(1, fileName.length - 1)
            }
        } else {
            fileName = URLUtil.guessFileName(url, contentDisposition, mimeType)
        }

        val cookie = CookieManager.getInstance().getCookie(url)
        request.addRequestHeader("Cookie", cookie)

        request.setMimeType(mimeType)
        request.addRequestHeader("User-Agent", userAgent)
        request.setDescription("Downloading File")
        request.setTitle(fileName)
        request.allowScanningByMediaScanner()
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName)

        dm.enqueue(request)
        Toast.makeText(this, "파일이 다운로드됩니다.", Toast.LENGTH_LONG).show()
    } catch (e: Exception) {
        e.printStackTrace()
    }
}