File Upload in WebView (Android)

The Android WebView by default doesn’t open file chooser for a HTML form input of type ‘file’. However, it is possible to make this work by overriding the hidden method openFileChooser, which needs to be overridden to pop up a file chooser and then return the result to WebView.

In com.phonegap.DroidGap class, add the openFileChooser method to GapClient:

Codes:
public class GapClient extends WebChromeClient {

...
// For Android < 3.0
public void openFileChooser(ValueCallback uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
DroidGap.this.startActivityForResult(
Intent.createChooser(i, "File Browser"),
FILECHOOSER_RESULTCODE);
}

// For Android 3.0+
public void openFileChooser( ValueCallback uploadMsg, String acceptType ) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
DroidGap.this.startActivityForResult(
Intent.createChooser(i, "File Browser"),
FILECHOOSER_RESULTCODE);
}

...

Add the following code to onActivityResult():
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage)
return;
Uri result = intent == null || resultCode != RESULT_OK ? null
: intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
} else {
super.onActivityResult(requestCode, resultCode, intent);
IPlugin callback = this.activityResultCallback;
if (callback != null) {
callback.onActivityResult(requestCode, resultCode, intent);
}
}
}

The webview will be able to pop up a file chooser and then return the chosen file.

Reference: http://stackoverflow.com/questions/5907369/file-upload-in-webview

Advertisements
Tagged , , ,

5 thoughts on “File Upload in WebView (Android)

  1. Choice Zeiss says:

    hello, I just do what you say and it now work ,can U give me your source code ? thx!

  2. I built an app using this code and it worked in 2.3.6 (API version 7), but the same app didn’t work in Android 4.0.3, nothing happens when I hit the button to select a file. Any ideas?

  3. anchal says:

    but its not working on nexus 4.1

  4. […] Android WebView File Upload File Upload in WebView (Android) [Android, Hybrid]openFileChooser 킷캣에서 동작하지 않는 문제( openFileChooser Kitkat […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: