How to Create a Android WebView with Image Upload and Download Feature

The code is an example of how to create an Android WebView with image upload and download feature. The WebView is a widget in Android that allows you to display web pages within your application. The code sets up a WebView with JavaScript and file access enabled. It also enables file upload from the WebView by setting a WebChromeClient that overrides the onShowFileChooser() method.

The onShowFileChooser() method sets up an intent to allow the user to select a file to upload. The result of the file selection is passed to a ValueCallback<Array<Uri>> object, which is then used to upload the file to the server.

Kotlin Code for WebView

class EditPhotoActivity : AppCompatActivity() {

        private lateinit var webView: WebView
        private var fileUploadCallback: ValueCallback<Array<Uri>>? = null

        private val fileUploadActivityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                val results = result.data?.let { WebChromeClient.FileChooserParams.parseResult(result.resultCode, it) }
                fileUploadCallback?.onReceiveValue(results)
            } else {
                fileUploadCallback?.onReceiveValue(null)
            }
            fileUploadCallback = null
        }

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_edit_photo)

            webView = findViewById(R.id.webView)

            // Enable JavaScript and file access in the WebView
            webView.settings.javaScriptEnabled = true
            webView.settings.allowFileAccess = true
            webView.settings.domStorageEnabled = true

            // Enable file upload from the WebView
            webView.webChromeClient = object : WebChromeClient() {
                override fun onShowFileChooser(
                    webView: WebView?,
                    filePathCallback: ValueCallback<Array<Uri>>?,
                    fileChooserParams: FileChooserParams?
                ): Boolean {
                    fileUploadCallback = filePathCallback ?: return false
                    val intent = fileChooserParams?.createIntent()
                    fileUploadActivityResultLauncher.launch(intent)
                    return true
                }
            }

            // Set up a WebViewClient to handle page navigation and downloads
            webView.webViewClient = object : WebViewClient() {
                override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
                    // Handle page navigation within the WebView
                    view?.loadUrl(request?.url.toString())
                    return true
                }

                override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {
                    // Handle downloads from the WebView
                    val url = request?.url.toString()
                    if (url?.endsWith(".jpg") == true || url?.endsWith(".png") == true || url?.endsWith(".gif") == true) {
                        val connection = URL(url).openConnection() as HttpURLConnection
                        connection.connect()
                        val inputStream = connection.inputStream
                        return WebResourceResponse("image/*", "UTF-8", inputStream)
                    }
                    return super.shouldInterceptRequest(view, request)
                }
            }

            // Load the website in the WebView
            webView.loadUrl("https://www.insertcart.com/")
        }
    }

The code also sets up a WebViewClient that handles page navigation and downloads. The shouldOverrideUrlLoading() method overrides the default behavior of the WebView to handle page navigation within the WebView. The shouldInterceptRequest() method intercepts requests for image files and returns a WebResourceResponse object that contains the image data.

Finally, the code loads a website (https://www.insertcart.com/) in the WebView. This code can be used as a starting point to create a WebView with image upload and download feature in an Android application.

Sandy

Sandy

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *
Email *