android h5选择手机图片或者文件示例

有时候有种需求,是从手机端的h5界面选择图片或者文件,这里需要用到

onShowFileChooser()方法,h5需要使用input 标签,直接上代码:
<!DOCTYPE html>
<html>

<body>
<input type="file"
       accept="image/*"
       id="inputimg"/>
<img id="image" style="width: 300px; height: 300px;">
<input type="button" value="点击Android被调用" onclick="window.android.back()"/>
</body>

<script type="text/javascript">

    var input = document.getElementById("inputimg");
    var image = document.getElementById("image");
    input.onchange = function () {
       var file = this.files[0];
       var url = URL.createObjectURL(file);
       image.src=url;
    }

  </script>

</html>

此html文件放入android工程中,如图:

public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        binding.webview.getSettings().setJavaScriptEnabled(true);
        binding.webview.loadUrl("file:///android_asset/test.html");
        binding.webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                                             FileChooserParams fileChooserParams) {
                // filePathCallback.onReceiveValue() 返回选择好的图片或文件给web端
                // fileChooserParams 从web端传递过来的参数,用于通知android端其需求,比如:image/*
                mFilePathCallback = filePathCallback;
                // 选择手机端的图片或者文件
                pickfile(fileChooserParams);
                return true;
            }
        });
    }

private void pickfile(WebChromeClient.FileChooserParams fileChooserParams) {
        Uri[] files = selectFile(fileChooserParams);
        // 把图片或文件传递给web端
        mFilePathCallback.onReceiveValue(files);
    }
<WebView
        android:id="@+id/webview"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="@color/white"
        android:text="@string/hello_first_fragment"
        app:layout_constraintBottom_toTopOf="@id/button_first"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

怎么使用这个函数,代码里面已经注释了,下面看看效果:

当然,具体选择图片或者文件的方法没标出,这里不作记录,因为可以找到很多第三方的库或者自己写一个工具类,

好了,又可以愉快玩耍了。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值