Android学习之实现WebView中input="file"选择文件,处理选择图片无法返回类型问题

// 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;
    }

你可能感兴趣的:(android,图片,input,网页,webView)