// js <input type="file" name="fileField" id="fileField" />
private ValueCallback<Uri> mUploadMessage;
private final int FILECHOOSER_RESULTCODE = 1;
// WebChromeClient , 。 :
private class MyWebChromeClient extends WebChromeClient{
// Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
this.openFileChooser(uploadMsg, "*/*");
}
// 3.0 +
public void openFileChooser( ValueCallback<Uri> uploadMsg, String acceptType ) {
this.openFileChooser(uploadMsg, acceptType, null);
}
// Android > 4.1.1
public void openFileChooser(final ValueCallback<Uri> uploadMsg, String acceptType, String capture)
{
mUploadMessage = uploadMsg; // uploadMsg
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(intent, FILECHOOSER_RESULTCODE);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (mUploadMessage == null)
return;
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
try {
mUploadMessage.onReceiveValue(Uri.fromFile(new File(getRealFilePath(context, result))));
} catch (Exception e) {
mUploadMessage = null;
e.printStackTrace();
}
mUploadMessage = null;
}
}
/**
* uri
* @param context
* @param uri
* @return
*/
private String getRealFilePath(Context context, Uri uri ) {
if ( null == uri ) return null;
final String scheme = uri.getScheme();
String data = null;
if ( scheme == null )
data = uri.getPath();
else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
data = uri.getPath();
} else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
Cursor cursor = context.getContentResolver().query( uri, new String[] { ImageColumns.DATA }, null, null, null );
if ( null != cursor ) {
if ( cursor.moveToFirst() ) {
int index = cursor.getColumnIndex( ImageColumns.DATA );
if ( index > -1 ) {
data = cursor.getString( index );
}
}
cursor.close();
}
}
return data;
}