星五博客

android webview 对网页的file upload进行支持

全局:

private ValueCallback<Uri> mUploadMessage;

private final static int FILECHOOSER_RESULTCODE = 1;

webview进行处理:

webview.setWebChromeClient(new WebChromeClient() {
super.onProgressChanged(view, progress);
}
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg,
String acceptType) {
if (mUploadMessage != null)
return;
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "选择文件"),
FILECHOOSER_RESULTCODE);
}

// For Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
openFileChooser(uploadMsg, "");
}

// For Android > 4.1.1
public void openFileChooser(ValueCallback<Uri> uploadMsg,
String acceptType, String capture) {
openFileChooser(uploadMsg, acceptType);
}
});

对选择操作的返回事件进行处理

@Override
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;
}
}

经以上三步,就支持文件上传了。

Java