每天学习一点点,成功增加一大步

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

Android zhanghui 135℃

问题场景

这几天在写一个 app 项目的时候,项目内置本地的 H5,H5 内使用了 layui 框架内的上传图片的操作,这个操作在 PC 的 Google Chrome 浏览器的移动模拟 H5 页面中没有问题,在手机中的自带浏览器中也没有问题,但在 app 的 webView 中始终没有作用(反应)。

看下 JS layui 部分的代码:

// 图片上传
layui.use(['upload', 'layer'], function () {
    var upload = layui.upload;
    var layer = layui.layer;

    var index;
    upload.render({
        elem: '#up-image'
        , accept: 'images'
        , exts: 'jpg|jpeg|png|gif'
        , url: '/upload'
        , before: function () {
            ……
        }
        , done: function (res) {
           ……
        }
        , error: function () {
            // 请求异常回调
        }
    });
});

出现问题后,首先需要webview 对 JS 的支持,即: setJavaScriptEnable (具体的设置本站中有记录,可看这里),可检查了一遍项目代码发现有这项的设置代码。于是呼又沉静在找到问题的原因与解决方法中,找了半天时间,终于找到问题的原因与解决方法。

问题的原因

Android 的 webView 默认是不支持文件上传的。即:

<input type="file"/>

解决的方法

1、需要授予的权限 READ_EXTERNAL_STORAGE 权限添加方式可看【Android permission 访问权限大全

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

3、完整的示例代码

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

注意:

  • 在 Acitivity 的 onActivityResult() 方法中处理,不管请求是否成功,我们都要在onReceiveValue()传null,否则html中的js执行一次就不会再执行,即我们点击不会在有响应了。
  • openImageChooserActivity 这个方法里可以选择上传的文件类型,可以限制为图片或者从文件夹中选择图片上传

转载请注明:隨習筆記 » webView支持H5页面通过js实现文件上传、图片上传

喜欢 (0)