Notice
Recent Posts
Recent Comments
Link
«   2025/01   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

Wook No.1

Webview 파일 다운로드 본문

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()
    }
}
Comments