后端jsp代码
<input type = "file">
点击选择文件时,需要告诉客户端,调起选择文件的Intent.
客户端代码:
private int REQUEST_CODE_FILE_CHOOSE = 1;
//此对象把选中的文件上传至webview
private ValueCallback<Uri[]> uploadMessageAboveL;
mWebview.setWebChromeClient(new WebChromeClient() {
@Override
//选择上传时,会调用此方法
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
uploadMessageAboveL = filePathCallback;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
//开启一个选择文件的activity
startActivityForResult(Intent.createChooser(intent, "Image Chooser"), REQUEST_CODE_FILE_CHOOSE);
return true;
}
});
这里参数 ValueCallback<Uri[]> filePathCallback
,是选择文件后,上传给webview所选文件的Uri的对象。换句话说,是用来给webview传递文件Uri数组的。(从泛型也能看出,这个对象只接收Uri类型)。
源代码如下:
public interface ValueCallback<T> {
/**
* Invoked when the value is available.
* @param value The value.
*/
public void onReceiveValue(T value);
};
选择文件后(这里是单选),调用如下方法:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
//传null值这段很有必要,用来避免不选择文件直接返回,导致再一次不能选择文件的问题
if (resultCode == RESULT_CANCELED){
if(uploadMessageAboveL!=null){
uploadMessageAboveL.onReceiveValue(null);}
}
Uri[] results = null;
if (resultCode == Activity.RESULT_OK) {
if(uploadMessageAboveL==null) return;
if (intent != null) {
String dataString = intent.getDataString();
ClipData clipData = intent.getClipData();
if (clipData != null) {
results = new Uri[clipData.getItemCount()];
for (int i = 0; i < clipData.getItemCount(); i++) {
ClipData.Item item = clipData.getItemAt(i);
results[i] = item.getUri();
}
}
if (dataString != null)
results = new Uri[]{Uri.parse(dataString)};
}
}
if(results!=null)
uploadMessageAboveL.onReceiveValue(results);
uploadMessageAboveL = null;
}
这里,intent传入了选择资源的信息,包括Uri等。
下面是debug跟到的intent的内容。
Intent { dat=content://com.google.android.apps.photos.contentprovider/-1/1/content://media/external/images/media/64/ORIGINAL/NONE/145107880 flg=0x1 clip={text/uri-list U:content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F64/ORIGINAL/NONE/145107880} }
选择文件后,就把intent中相关的内容转换成Uri,再通过uploadMessageAboveL传到webview。
由webview完成后续的处理。