By default, webViews on Android do not support uploading files. And this, also in our front end engineer informed after understanding. Because each version of Android WebView implementation is different, so need to adapt to different versions. After a little time and reference to other people’s code, the problem has been solved. Here are the potholes I stepped on.
The main idea is to override the WebChromeClient and then receive the selected file Uri in the WebViewActivity and pass it to the page to upload.
Create an inner class for WebViewActivity
|
The above openFileChooser is an unexposed interface of the system, so there is no need to add the annotation of Override. Meanwhile, different versions have different parameters. The first parameter, ValueCallback, is used to receive the file callback to the webpage after we select the file. AcceptType indicates the MIME type of the accepted file. After Android 5.0, onShowFileChooser was provided to allow us to implement the file selection method, which still has ValueCallback, and also includes acceptType in the FileChooserParams parameter. We can open the system’s file selector according to acceptType or we can create our own file selector. Of course, if you want to open the camera to take a photo, you can also use the Intent to open the camera to take a photo.
Process the selected file
The above is to open the response to select the file interface, we also need to deal with the receipt of the file, to the web page to respond. Because we opened the selection page using startActivityForResult, we will receive the selection result in onActivityResult. Show code:
|
The above code basically calls ValueCallback’s onReceiveValue method and sends the result back to the Web.
Notice what else is important
For Android versions 5.0 or later, The onReceiveValue of ValueCallback receives a Uri. For Android versions 5.0 or later, the onReceiveValue of ValueCallback receives a Uri array.
Select a file using a component provided by the system or other supported app. The uri returned is either the URL of the file directly or the URI of the ContentProvider. Therefore, we need to unify the processing and convert it into the URI of the file.
Calling getPath converts the Uri to the Path of the real file, and you can then generate the Uri of the file yourself
|
Again, even if the obtained results is null, also want to the web, namely direct call mUploadMessage. OnReceiveValue (null), or web pages will be blocked.
And finally, when we’re releasing the release package, because we’re going to get confused, we’re going to set it up specifically not to confuse the openFileChooser method in the WebChromeClient subclass, because it’s not an inherited method, so it’s going to get confused by default, and we’re not going to be able to select the file.
That’s it.
The original address: blog. Isming. Me / 2015/12/21 /… Please indicate the source.