本文主要是介绍WebView支持input type=file调起本地文件,获取图片,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
最近一个活动要求上传图片功能,WebView获取本地图片文件,但是在iOS上<input type="file">
可以调起他们的本地文件,在android上点击没有反应,后来看了一些资料,发现这个方法在android 上没有作用,需要我们自己做处理,以下附上代码:
activity文件:
public class MainActivity extends AppCompatActivity {private ValueCallback<Uri> mUploadMessage;// 表单的数据信息private ValueCallback<Uri[]> mUploadCallbackAboveL;private final static int FILECHOOSER_RESULTCODE = 1;// 表单的结果回调</span>private Uri imageUri;private WebView mWebView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main2);mWebView= (WebView) findViewById(R.id.webview);mWebView.loadUrl("网页地址");mWebView.getSettings().setJavaScriptEnabled(true);mWebView.setWebViewClient(new WebViewClient() {@Overridepublic boolean shouldOverrideUrlLoading(WebView view, String url) {return super.shouldOverrideUrlLoading(view, url);}});mWebView.setWebChromeClient(new WebChromeClient() {@Overridepublic boolean onShowFileChooser(WebView webView,ValueCallback<Uri[]> filePathCallback,FileChooserParams fileChooserParams) {mUploadCallbackAboveL = filePathCallback;take();return true;}});}@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);if (requestCode == FILECHOOSER_RESULTCODE) {if (null == mUploadMessage && null == mUploadCallbackAboveL) return;Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();if (mUploadCallbackAboveL != null) {onActivityResultAboveL(requestCode, resultCode, data);} else if (mUploadMessage != null) {if (result != null) {String path = getPath(getApplicationContext(),result);Uri uri = Uri.fromFile(new File(path));mUploadMessage.onReceiveValue(uri);} else {mUploadMessage.onReceiveValue(imageUri);}mUploadMessage = null;}}}@SuppressWarnings("null")@android.support.annotation.RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {if (requestCode != FILECHOOSER_RESULTCODE|| mUploadCallbackAboveL == null) {return;}Uri[] results = null;if (resultCode == Activity.RESULT_OK) {if (data == null) {results = new Uri[]{imageUri};} else {String dataString = data.getDataString();ClipData clipData = data.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) {mUploadCallbackAboveL.onReceiveValue(results);mUploadCallbackAboveL = null;} else {results = new Uri[]{imageUri};mUploadCallbackAboveL.onReceiveValue(results);mUploadCallbackAboveL = null;}return;}private void take() {File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyApp");if (!imageStorageDir.exists()) {imageStorageDir.mkdirs();}File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");imageUri = Uri.fromFile(file);final List<Intent> cameraIntents = new ArrayList<Intent>();final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);final PackageManager packageManager = getPackageManager();final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);for (ResolveInfo res : listCam) {final String packageName = res.activityInfo.packageName;final Intent i = new Intent(captureIntent);i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));i.setPackage(packageName);i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);cameraIntents.add(i);}Intent i = new Intent(Intent.ACTION_GET_CONTENT);i.addCategory(Intent.CATEGORY_OPENABLE);i.setType("image/*");Intent chooserIntent = Intent.createChooser(i, "Image Chooser");MainActivity.this.startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);}@SuppressLint("NewApi")@TargetApi(Build.VERSION_CODES.KITKAT)public static String getPath(final Context context, final Uri uri) {final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;// DocumentProviderif (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {// ExternalStorageProviderif (isExternalStorageDocument(uri)) {final String docId = DocumentsContract.getDocumentId(uri);final String[] split = docId.split(":");final String type = split[0];if ("primary".equalsIgnoreCase(type)) {return Environment.getExternalStorageDirectory() + "/" + split[1];}} else if (isDownloadsDocument(uri)) {final String id = DocumentsContract.getDocumentId(uri);final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));return getDataColumn(context, contentUri, null, null);} else if (isMediaDocument(uri)) {final String docId = DocumentsContract.getDocumentId(uri);final String[] split = docId.split(":");final String type = split[0];Uri contentUri = null;if ("image".equals(type)) {contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;} else if ("video".equals(type)) {contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;} else if ("audio".equals(type)) {contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;}final String selection = "_id=?";final String[] selectionArgs = new String[]{split[1]};return getDataColumn(context, contentUri, selection, selectionArgs);}} else if ("content".equalsIgnoreCase(uri.getScheme())) {return getDataColumn(context, uri, null, null);} else if ("file".equalsIgnoreCase(uri.getScheme())) {return uri.getPath();}return null;}public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {Cursor cursor = null;final String column = "_data";final String[] projection = {column};try {cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);if (cursor != null && cursor.moveToFirst()) {final int column_index = cursor.getColumnIndexOrThrow(column);return cursor.getString(column_index);}} finally {if (cursor != null) cursor.close();}return null;}public static boolean isExternalStorageDocument(Uri uri) {return "com.android.externalstorage.documents".equals(uri.getAuthority());}public static boolean isDownloadsDocument(Uri uri) {return "com.android.providers.downloads.documents".equals(uri.getAuthority());}public static boolean isMediaDocument(Uri uri) {return "com.android.providers.media.documents".equals(uri.getAuthority());}// 捕捉“回退”按键,让WebView能回退到上一页,而不是直接关闭Activity。@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {mWebView.goBack();return true;}return super.onKeyDown(keyCode, event);}}
重写WebChromeClient(),在onShowFileChooser()里处理文件;
在onActivityResult()获取文件回调;
效果如下:
注:因为活动已结束,所以地址没有放,效果如图所示;布局文件就是简单的webview ;
这篇关于WebView支持input type=file调起本地文件,获取图片的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!