在2021年,我是这样做的:
在MainActivity中,定义assetLoader:
private lateinit var assetLoader: WebViewAssetLoader
在MainActivity.onCreate()中,定义您想要为webview资产加载器提供的本地目录:
val publicDir: File = File(this.applicationContext.cacheDir, "public")
assetLoader = WebViewAssetLoader.Builder()
.setDomain("you website domain")
.addPathHandler("/public/", InternalStoragePathHandler(this.applicationContext, publicDir))
.build()
mWebView.webViewClient = object : WebViewClientCompat() {
@RequiresApi(21)
override fun shouldInterceptRequest(
view: WebView,
request: WebResourceRequest
): WebResourceResponse? {
val res: WebResourceResponse? = assetLoader.shouldInterceptRequest(request.url)
return res
}
// to support API < 21
override fun shouldInterceptRequest(
view: WebView,
url: String
): WebResourceResponse? {
return assetLoader.shouldInterceptRequest(Uri.parse(url))
}
}
将onActivityResult()添加到MainActivity中:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
val result = CropImage.getActivityResult(data)
if (resultCode == RESULT_OK) {
val resultUri: Uri = result.uri
val filePath = resultUri.path
// parse the filePath to find the directory and the file name. Note you may need to change the number 22 to some other number to find the delimiter / between the path and the file name.
val index: Int = filePath!!.indexOf("com.your.package/cache") + 22
val imageFileName = filePath.substring(index)
val imageFile = File(filePath)
// move the cropped image to the public subdirectory
val publicFileDir = File(filePath.substring(0, index) + "public/")
publicFileDir.mkdirs()
imageFile.renameTo(File(publicFileDir, imageFileName))
// change the image src in webview
val imageUrl: String = "/public/" + imageFileName
mWebView.evaluateJavascript("$('#image').attr('src', '$imageUrl');", null)
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
val error = result.error
Toast.makeText(this@MainActivity, "Error in picking an image.", Toast.LENGTH_LONG).show()
}
}
}
在这里,我将“com.your.package/cache/public”作为资产文件夹提供给WebView,并将其作为“/public”可用。换句话说,WebView将解释https://your.domain/public/image_file为位于com.your.package/cache/public/image_file的本地文件。 WebViewAssetLoader的重要性在于现在您的本地文件将通过与您的服务器上html文件相同域的URL访问,绕过同源策略(SOP)限制。