(Android/안드로이드) WebView에서 파일 업로드 구현 방법 - input type="file" 처리 가이드

개요


1. WebView 파일 업로드는 어떻게 동작하나?


2. 기본 구현 구조


3. WebView 기본 세팅


4. 가장 기본적인 파일 업로드 구현

4.1 콜백 변수 선언

private var filePathCallback: ValueCallback<Array<Uri>>? = null

4.2 Activity Result API 등록

private val fileChooserLauncher =
    registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        val callback = filePathCallback ?: return@registerForActivityResult

        val uris = WebChromeClient.FileChooserParams.parseResult(
            result.resultCode,
            result.data
        )

        callback.onReceiveValue(uris)
        filePathCallback = null
    }

4.3 WebChromeClient 구현

inner class CustomWebChromeClient : WebChromeClient() {

    override fun onShowFileChooser(
        webView: WebView?,
        filePathCallback: ValueCallback<Array<Uri>>?,
        fileChooserParams: FileChooserParams?
    ): Boolean {
        this@WebViewActivity.filePathCallback?.onReceiveValue(null)
        this@WebViewActivity.filePathCallback = filePathCallback

        val intent = fileChooserParams?.createIntent()
        return try {
            fileChooserLauncher.launch(intent)
            true
        } catch (e: Exception) {
            this@WebViewActivity.filePathCallback = null
            false
        }
    }
}

5. Android 13 이상 권한 이슈


6. 자주 터지는 실수


7. 실무에서 추천하는 구조

WebViewActivity / WebViewFragment
        ↓
WebFileChooserManager
        ↓
- chooser intent 생성
- camera uri 생성
- 결과 파싱
- callback 전달


Related Posts