You have a form on WebView, with input type as “file”, and want to allow the user to upload a file from his device. Prior to Lollipop, this was not very straightforward, and you had to resort to using private APIs, which has always been discouraged. But, you had to do it. With Lollipop, there’s a new public API, which still isn’t very straight-forward to use, but at-least, should be reliable and compatible with newer Android/WebView versions. So, how do you implement File Upload from WebView on Android with the new public API?
This has been a long pending request, and people have implemented workarounds by using various versions of some private API’s for various older versions of Android.
Steps to Implement (3 steps)
- Attach WebViewChromeClient, and override method callback for a click event on and input field of type file.
mWebView.setWebChromeClient(new WebChromeClient() { @Override public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) { mFilePathCallback = filePathCallback; // Launch Intent for picking file return true; } });
- Launch Intent for picking the file
Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); startActivityForResult(intent, PICKFILE_REQUEST_CODE);
- Pass the Uri of the selected file to WebView
@Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == PICKFILE_REQUEST_CODE) { Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData(); Uri[] resultsArray = new Uri[1]; resultsArray[0] = result; mFilePathCallback.onReceiveValue(resultsArray); } }
I have created a small sample project with all the required code to achieve a simple input field taking in an image. You can get the source on Github.
Sorry. I have a problem. Chromewebview client links go to another browser. How i fix it ?
Can you try this? Is this the problem?
http://www.makeuseof.com/tag/remove-change-set-default-apps-android/
Are you hosting this file somewhere?
webView.loadUrl(“http://10.0.1.27:3000/input.html”);
Yes. It’s an application on my other system.