Programming/WebView

WebView에서 파일 업로드 및 다운로드 처리

DOTI 2025. 4. 14. 15:09
WebView에서 파일 업로드 및 다운로드 처리
반응형

 

WebView에서는 파일 업로드와 다운로드를 처리할 수 있습니다. 이번 글에서는 WebView 내에서 파일 업로드 및 다운로드 기능을 구현하는 방법을 다루겠습니다.

1. WebView에서 파일 업로드 처리

WebView에서 파일 업로드를 처리하려면 WebChromeClientonShowFileChooser() 메서드를 오버라이드하여 파일 선택 기능을 추가해야 합니다.

webView.setWebChromeClient(new WebChromeClient() {
    @Override
    public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
        mUploadMessage = filePathCallback;
        Intent intent = fileChooserParams.createIntent();
        try {
            startActivityForResult(intent, FILE_CHOOSER_RESULT_CODE);
        } catch (ActivityNotFoundException e) {
            mUploadMessage = null;
            Toast.makeText(MainActivity.this, "파일 선택기를 사용할 수 없습니다.", Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }
});

파일 선택 후, 선택된 파일의 URI를 filePathCallback를 통해 전달합니다. 이를 통해 선택된 파일을 처리할 수 있습니다.

2. WebView에서 파일 다운로드 처리

WebView에서 파일 다운로드를 처리하려면 WebViewClientshouldOverrideUrlLoading() 메서드를 오버라이드하여 다운로드를 감지하고 처리할 수 있습니다.

webView.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.endsWith(".pdf") || url.endsWith(".jpg")) {
            // 파일 다운로드 처리
            downloadFile(url);
            return true;
        }
        return super.shouldOverrideUrlLoading(view, url);
    }
});

private void downloadFile(String url) {
    // 다운로드 코드 구현 (파일 다운로드 로직)
}

이렇게 하면 WebView 내에서 특정 파일 형식을 감지하고, 다운로드를 처리할 수 있습니다.

정리

  • 파일 업로드 기능을 위한 onShowFileChooser() 메서드 구현
  • 파일 다운로드 기능을 위한 shouldOverrideUrlLoading() 메서드 구현
  • 파일 형식에 따른 다운로드 처리

WebView에서 파일 업로드와 다운로드 기능을 쉽게 처리할 수 있습니다. 다음 글에서는 WebView와 Android 네이티브 코드 간의 통합 방법에 대해 다루겠습니다.

반응형