Wook No.1
Webview 파일 다운로드 본문
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()
}
}
'Android' 카테고리의 다른 글
카카오톡 로그인 AuthError statusCode=302 KakaoTalk is installed but not connected to Kakao account. (0) | 2023.04.20 |
---|---|
[에러]Unknown host CPU architecture: arm64 , Android NDK (0) | 2023.02.06 |
Gradle Repository 등록시 프로토콜 보안 오류 (0) | 2022.09.15 |
Android 라이브러리 Maven 배포 (0) | 2022.09.15 |
Android 라이브러리 만들기(AAR) (0) | 2022.09.15 |
Comments