File Upload in WebView

后端 未结 19 1909
旧巷少年郎
旧巷少年郎 2020-11-22 00:28

I have been struggling to upload files from WebView since last few days and there is no progress. I googled and implemented all suggested solutions but none works, like: sol

19条回答
  •  不知归路
    2020-11-22 00:55

    In 5.0 Lollipop, Google added an official method, WebChromeClient.onShowFileChooser. They even provide a way to automatically generate the file chooser intent so that it uses the input accept mime types.

    public class MyWebChromeClient extends WebChromeClient {
            // reference to activity instance. May be unnecessary if your web chrome client is member class.
        private MyActivity activity;
    
        public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, FileChooserParams fileChooserParams) {
            // make sure there is no existing message
            if (myActivity.uploadMessage != null) {
                myActivity.uploadMessage.onReceiveValue(null);
                myActivity.uploadMessage = null;
            }
    
            myActivity.uploadMessage = filePathCallback;
    
            Intent intent = fileChooserParams.createIntent();
            try {
                myActivity.startActivityForResult(intent, MyActivity.REQUEST_SELECT_FILE);
            } catch (ActivityNotFoundException e) {
                myActivity.uploadMessage = null;
                Toast.makeText(myActivity, "Cannot open file chooser", Toast.LENGTH_LONG).show();
                return false;
            }
    
            return true;
        }
    }
    
    
    public class MyActivity extends ... {
        public static final int REQUEST_SELECT_FILE = 100;
        public ValueCallback uploadMessage;
    
        protected void onActivityResult(int requestCode, int resultCode, Intent data){
            if (requestCode == REQUEST_SELECT_FILE) {
                    if (uploadMessage == null) return;
                    uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
                    uploadMessage = null;
                }
            }
        }
    }
    

    For Android versions before KitKat, the private methods mentioned in the other answers work. I have not found a good workaround for KitKat (4.4).

提交回复
热议问题