让Android中的webview支持页面中的文件上传

来源:互联网 发布:装饰报价软件 编辑:程序博客网 时间:2024/06/07 08:11

android webview在默认情况下是不支持网页中的文件上传功能的;

如果在网页中有<input type="file" />,在android webview中访问时也会出现浏览文件的按钮

但是点击按钮之后没有反应...

那么如何能够让android的webview能够响应,这个浏览按钮呢?

我们需要为webview设置WebChromeClient,在WebChromeClient的实现类中覆盖文件选择的方法:

/***************** android中使用WebView来打开本机的文件选择器 *************************/// js上传文件的<input type="file" name="fileField" id="fileField" />事件捕获// Android > 4.1.1 调用这个方法public void openFileChooser(ValueCallback<Uri> uploadMsg,String acceptType, String capture) {mUploadMessage = uploadMsg;Intent intent = new Intent(Intent.ACTION_GET_CONTENT);intent.addCategory(Intent.CATEGORY_OPENABLE);intent.setType("image/*");context.startActivityForResult(Intent.createChooser(intent, "完成操作需要使用"),WebMainActivity.FILECHOOSER_RESULTCODE);}// 3.0 + 调用这个方法public void openFileChooser(ValueCallback<Uri> uploadMsg,String acceptType) {mUploadMessage = uploadMsg;Intent intent = new Intent(Intent.ACTION_GET_CONTENT);intent.addCategory(Intent.CATEGORY_OPENABLE);intent.setType("image/*");context.startActivityForResult(Intent.createChooser(intent, "完成操作需要使用"),WebMainActivity.FILECHOOSER_RESULTCODE);}// Android < 3.0 调用这个方法public void openFileChooser(ValueCallback<Uri> uploadMsg) {mUploadMessage = uploadMsg;Intent intent = new Intent(Intent.ACTION_GET_CONTENT);intent.addCategory(Intent.CATEGORY_OPENABLE);intent.setType("image/*");context.startActivityForResult(Intent.createChooser(intent, "完成操作需要使用"),WebMainActivity.FILECHOOSER_RESULTCODE);}/************** end ***************/

在设置WebChromeClient时,要传入一个ValueCallback<Uri> mUploadMessage,同时传入webview所在的Activity的对象;

在WebChromeClient的实现类中对应的文件选择事件响应的方法里,使用webview所在的activity对象开启一个android文件选择器,

使用startActivityForResult方法,在开启的文件选择activity结束后需要返回一个值;在webview所在的activity中通过覆盖Activity的onActivityResult方法,得到所需的结果,即选择文件的url

        /** * 返回文件选择 */@Overrideprotected void onActivityResult(int requestCode, int resultCode,Intent intent) {if (requestCode == FILECHOOSER_RESULTCODE) {mUploadMessage = mWebChromeClient.getmUploadMessage();if (null == mUploadMessage)return;Uri result = intent == null || resultCode != RESULT_OK ? null: intent.getData();mUploadMessage.onReceiveValue(result);mUploadMessage = null;}}
完成上述操作后就成功的实现了android webview支持文件上传。。。






原创粉丝点击