android WebView的网页上传文件
16lz
2021-01-23
android WebView 网页上传文件(图片资源等)
网页访问本地资源有两种方法:1可以通过js互调,原生代码提供对应的方法;2网页中标签,访问本地资源。本文主要讲的就是2 。
具体代码(以Webview在Activity中为列)
ValueCallback mUploadMessages; ValueCallback mUploadMessage; int FILECHOOSER_RESULTCODE = 100; WebChromeClient wvcc = new WebChromeClient() { // For Android 3.0- public void openFileChooser(ValueCallback uploadMsg) { Log.d(TAG, "openFileChoose(ValueCallback uploadMsg)" ); mUploadMessage = uploadMsg; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("*/*"); startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE); } // For Android 3.0+ public void openFileChooser( ValueCallback uploadMsg, String acceptType ) { Log.d(TAG, "openFileChoose( ValueCallback uploadMsg, String acceptType )"); mUploadMessage = uploadMsg; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("*/*"); startActivityForResult( Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE); } //For Android 4.1 public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture){ Log.d(TAG, "openFileChoose(ValueCallback uploadMsg, String acceptType, String capture)" ); mUploadMessage = uploadMsg; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("*/*"); startActivityForResult( Intent.createChooser( i, "File Browser" ), FILECHOOSER_RESULTCODE ); } // For Android 5.0+ public boolean onShowFileChooser (WebView webView, ValueCallback filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) { Log.d(TAG, "onShowFileChooser(ValueCallback uploadMsg, String acceptType, String capture)" ); mUploadMessages = filePathCallback; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("*/*"); startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE); return true; } }; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == FILECHOOSER_RESULTCODE ) { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){ if (null == mUploadMessages ) return; mUploadMessages.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data)); mUploadMessages = null; }else { if (null == mUploadMessage) return; Uri result = data == null || resultCode != RESULT_OK ? null : data.getData(); mUploadMessage.onReceiveValue(result); mUploadMessage = null; } } }
- 在WebView设置好 setWebChromeClient(wvcc);
在具体项目中已使用。
更多相关文章
- 用HTML+JS实现Android闹钟功能,附带Alarm代码分享
- Android JUnit Test——批量运行测试代码
- Android 网页抓取(实现新闻客户端)
- 在 Android 使用 Support Annotations 注解优化代码
- Android判断网络连接是否可用(代码)
- Android中使用代码开关GPS、移动网络(GPRS)、WiFi
- Android Studio访问Http资源之HttpURLConnection的案例(GET方式)