Android webview支持H5页面通过js实现文件上传、图片上传

一、问题场景:

项目中遇到通过网页上传文件的需求,IOS直接是支持的,安卓端却没反应,有些机型甚至闪退。其实是Android的webview默认是不支持<input type="file"/>文件上传的。现在的前端页面需要处理的是:

        1.打开本地文件选择器

        2.用户选择需要上传的文件

        3.处理用户选择的文件通知webview

        4.前端提交表单上传文件

        首先需要webview 对 JS 的支持,即 webview.getSettings().setJavaScriptEnable(true);其次要注意前端页面针对不同版本的android系统 webview内核会有不同,调用方法是不一样的。

二、问题解决:

1.需要授予的权限

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

2.针对不同系统的处理

webview.setWebChromeClient(new WebChromeClient() {

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> valueCallback) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android  >= 3.0
            public void openFileChooser(ValueCallback valueCallback, String acceptType) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            //For Android  >= 4.1
            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android >= 5.0
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                uploadMessageAboveL = filePathCallback;
                openImageChooserActivity();
                return true;
            }
        });

三、完整代码:

package com.wwy.test.webview_takepicture_upload_demo;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.wwy.mytest.webview_takepicture_upload_demo.R;

public class WebViewActivity extends AppCompatActivity {


    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private final static int FILE_CHOOSER_RESULT_CODE = 10000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);

        WebView webview = (WebView) findViewById(R.id.web_view);
        WebSettings settings = webview.getSettings();
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setJavaScriptEnabled(true);
        // 1.设置WebChromeClient,重写文件上传回调
        webview.setWebChromeClient(new WebChromeClient() {

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> valueCallback) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android  >= 3.0
            public void openFileChooser(ValueCallback valueCallback, String acceptType) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            //For Android  >= 4.1
            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
                uploadMessage = valueCallback;
                openImageChooserActivity();
            }

            // For Android >= 5.0
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                uploadMessageAboveL = filePathCallback;
                openImageChooserActivity();
                return true;
            }
        });
        //加载本地网页
        String targetUrl = "file:///android_asset/takePicture-upload/index.html";
        webview.loadUrl(targetUrl);
    }

    // 2.回调方法触发本地选择文件
    private void openImageChooserActivity() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
//        i.setType("image/*");//图片上传
//        i.setType("file/*");//文件上传
          i.setType("*/*");//文件上传
        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);
    }

    // 3.选择图片后处理
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (null == uploadMessage && null == uploadMessageAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            // Uri result = (((data == null) || (resultCode != RESULT_OK)) ? null : data.getData());
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        } else {
            //这里uploadMessage跟uploadMessageAboveL在不同系统版本下分别持有了
            //WebView对象,在用户取消文件选择器的情况下,需给onReceiveValue传null返回值
            //否则WebView在未收到返回值的情况下,无法进行任何操作,文件选择器会失效
            if (uploadMessage != null) {
                uploadMessage.onReceiveValue(null);
                uploadMessage = null;
            } else if (uploadMessageAboveL != null) {
                uploadMessageAboveL.onReceiveValue(null);
                uploadMessageAboveL = null;
            }
        }
    }

    // 4. 选择内容回调到Html页面
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null)
            return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.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)};
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }
}

       注意:

                1.最后我们在Acitivity的onActivityResult()方法中处理,不管请求是否成功,我们都要在onReceiveValue()传null,

                  否则html中的js执行一次就不会再执行,即我们点击不会在有响应了。

                2.这个方法里可以选择上传的文件类型,可以限制为图片或者从文件夹中选择图片上传:       

    private void openImageChooserActivity() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
//        i.setType("image/*");//图片上传
//        i.setType("file/*");//文件上传
          i.setType("*/*");//文件上传
        startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);
    }

(1)下图为 i.setType("*/*");

(2)下图为 i.setType("file/*");

四、引申其他一些设置

Android及iOS的webview的引擎都是webkit,对H5提供支持。

webview有两个方法:setWebChromeClient 和setWebClientsetWebClient
WebChromeClient:辅助WebView处理Javascript的对话框,网站图标,网站title,加载进度等
WebViewClient就是帮助WebView处理各种通知、请求事件的。


WebSetting常用方法总结:

1.setJavaScriptEnabled(true); //支持js 

2.setPluginsEnabled(true); //支持插件 

3.setUseWideViewPort(false); //将图片调整到适合webview的大小 

4.setSupportZoom(true); //支持缩放 

5.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); //支持内容重新布

6.supportMultipleWindows(); //多窗口 

7.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存 

8.setAllowFileAccess(true); //设置可以访问文件 

9.setNeedInitialFocus(true); //当webview调用requestFocus时为webview设置节点 webview

10. webSettings.setBuiltInZoomControls(true); //设置支持缩放 

11.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口 

12.setLoadWithOverviewMode(true); // 缩放至屏幕的大小 

13.setLoadsImagesAutomatically(true); //支持自动加载图片

部分内容参考了https://www.jianshu.com/p/fea5e829b30a,里面有更多的webview常见问题有空可以看看。

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页