FIleupload在Webview中不起作用?

时间:2018-06-25 12:55:35

标签: android file-upload webview

我正在尝试在网页视图中加载网页。该网页上有一个文件上传按钮。当我尝试在浏览器中打开网页时。 fileupload按钮可以正常工作。但是,当我在Webview中加载它并尝试使用fileupload时,它就无法工作。我怎么可能做错了。

    import android.app.Activity;
    import android.os.Bundle;
    import android.support.annotation.Nullable;
    import android.webkit.WebView;



    public class Testusers extends Activity {

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


            WebView wb = (WebView)findViewById(R.id.testview);
            wb.loadUrl("https://immense-mesa-73659.herokuapp.com/");
            wb.getSettings().setJavaScriptEnabled(true); // enable javascript

        }
    }

Permissions:-

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

xml layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <WebView
            android:id="@+id/testview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:layout_editor_absoluteX="8dp"
            tools:layout_editor_absoluteY="8dp" />


    </RelativeLayout>


</android.support.constraint.ConstraintLayout>

1 个答案:

答案 0 :(得分:1)

附加WebViewChromeClient,并为文件类型和输入字段上的click事件覆盖方法回调。

testview.setWebChromeClient(new WebChromeClient() {

    @Override
     public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,              FileChooserParams fileChooserParams) {
             mFilePathCallback = filePathCallback;
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            startActivityForResult(intent, PICKFILE_REQUEST_CODE);
            return true;
     }
});

将所选文件的Uri传递到WebView。

@Override
protected void onActivityResult(int requestCode, int resultCode,
 Intent intent) {
 if (requestCode == PICKFILE_REQUEST_CODE) {
      Uri result = intent == null || resultCode != RESULT_OK ? null
          : intent.getData();
      Uri[] resultsArray = new Uri[1];
      resultsArray[0] = result;
      mFilePathCallback.onReceiveValue(resultsArray);
 }
}