Tag Archives: upload

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 , , ,