当前位置: 首页 > 知识库问答 >
问题:

Android Webview文件和相机上传-Kotlin

吕霍英
2023-03-14
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        {
            if(requestCode == REQUEST_SELECT_FILE){
                if(uploadMessage != null){
                    uploadMessage?.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode,data))
                    uploadMessage = null
                }
            }
        }else if(requestCode == FILECHOOSER_RESULTCODE){
            if(mUploadMessage!=null){
                var result = data?.data
                mUploadMessage?.onReceiveValue(result)
                mUploadMessage = null
            }
        }else{
            Toast.makeText(this,"Failed to open file uploader, please check app permissions.",Toast.LENGTH_LONG).show()
            super.onActivityResult(requestCode, resultCode, data)
        }
 // For 3.0+ Devices (Start)
            // onActivityResult attached before constructor
            fun openFileChooser(uploadMsg : ValueCallback<Uri>, acceptType:String) {
                mUploadMessage = uploadMsg
                val i = Intent(Intent.ACTION_GET_CONTENT)
                i.addCategory(Intent.CATEGORY_OPENABLE)
                i.type = "*/*"
                startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE)
            }

            // For Lollipop 5.0+ Devices
            override fun onShowFileChooser(mWebView:WebView, filePathCallback:ValueCallback<Array<Uri>>, fileChooserParams:WebChromeClient.FileChooserParams):Boolean {
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
                    if (uploadMessage != null) {
                        uploadMessage?.onReceiveValue(null)
                        uploadMessage = null
                    }
                    uploadMessage = filePathCallback
                    val intent = fileChooserParams.createIntent()
                    try {
                        startActivityForResult(intent, REQUEST_SELECT_FILE)
                    } catch (e:ActivityNotFoundException) {
                        uploadMessage = null
                        Toast.makeText(getApplicationContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show()
                        return false
                    }
                    return true
                }else{
                    return false
                }
            }

            //For Android 4.1 only
            fun openFileChooser(uploadMsg:ValueCallback<Uri>, acceptType:String, capture:String) {
                mUploadMessage = uploadMsg
                val intent = Intent(Intent.ACTION_GET_CONTENT)
                intent.addCategory(Intent.CATEGORY_OPENABLE)
                intent.type = "*/*"
                startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE)
            }

            fun openFileChooser(uploadMsg:ValueCallback<Uri>) {
                //filePermission()
                mUploadMessage = uploadMsg
                val i = Intent(Intent.ACTION_GET_CONTENT)
                i.addCategory(Intent.CATEGORY_OPENABLE)
                i.type = "*/*"
                startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE)
            }

此外,文件浏览器在选择存储在设备本身的图像/PDF时工作,但通过这种方法从Google Drive上传的文件不能正确上传。有什么想法吗?

共有1个答案

杜英叡
2023-03-14

您可能没有添加下面的代码

webview.getSettings().setDomStorageEnabled(true);
webview.getSettings().setAllowContentAccess(true);
webview.getSettings().setAllowFileAccess(true);

这里我已经详细地给出了答案。希望这对你有帮助。如果你有任何疑问,让我知道。

编辑

全局声明以下变量

var requiredPermissions = arrayOf<String>(Permissions.CAMERA, Permissions.WRITE_EXTERNAL_STORAGE, Permissions.READ_EXTERNAL_STORAGE/*, Permissions.WRITE_SETTINGS*/)

val REQUEST_SELECT_FILE = 100
private val FILECHOOSER_RESULTCODE = 1
var uploadMessage: ValueCallback<Array<Uri>>? = null

var link: String? = null
private var mUploadMessage: ValueCallback<*>? = null

科特林码:

@SuppressLint("SetJavaScriptEnabled")
private fun startWebView(url: String) {
    // Create new webview Client to show progress dialog
    // When opening a url or click on link
    // Javascript enabled on webview
    mWebView.settings.javaScriptEnabled = true
    mWebView.settings.builtInZoomControls = true
    mWebView.settings.displayZoomControls = true
    mWebView.settings.domStorageEnabled = true
    mWebView.settings.allowContentAccess = true
    mWebView.settings.setAppCacheEnabled(false)
    mWebView.settings.cacheMode = WebSettings.LOAD_NO_CACHE
    mWebView.settings.setGeolocationEnabled(true)      // life saver, do not remove
    mWebView.addJavascriptInterface(WebAppInterface(this), "Android")
    mWebView.webChromeClient = MyWebChromeClient()
    mWebView.webViewClient = object : WebViewClient() {

        // If you will not use this method url links are open in new browser
        // not in webview
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            view.loadUrl(url)
            return true
        }

        override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                view.loadUrl(request.url.toString())
            }
            return true
        }

        override fun onReceivedError(view: WebView?, errorCode: Int, description: String?, failingUrl: String?) {
            super.onReceivedError(view, errorCode, description, failingUrl)
            util._log(TAG, "onReceivedError ")
        }

        // Show loader on url load
        override fun onLoadResource(view: WebView, url: String) {
        }

        override fun onPageFinished(view: WebView, url: String) {
            super.onPageFinished(view, url)
            progressBar.visibility = View.GONE
        }

        override fun onReceivedHttpError(view: WebView?, request: WebResourceRequest?, errorResponse: WebResourceResponse?) {
            super.onReceivedHttpError(view, request, errorResponse)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                util._log(TAG, "onReceivedHttpError ${errorResponse?.statusCode}")
            }
        }

        override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) {
            super.onReceivedError(view, request, error)
            util._log(TAG, "onReceivedError ")
            WebViewClient.ERROR_AUTHENTICATION
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                util._log(TAG, "error code: ${error.errorCode} " + request.url.toString() + " , " + error.description)
            }
        }

        override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
            super.onReceivedSslError(view, handler, error)
            util._log(TAG, "SSl error ")
        }
    }

    // Other webview options
    /*
     * mWebView.getSettings().setLoadWithOverviewMode(true);
     * mWebView.getSettings().setUseWideViewPort(true);
     * mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
     * mWebView.setScrollbarFadingEnabled(false);
     * mWebView.getSettings().setBuiltInZoomControls(true);
     */


    // Load url in webview

    if (NetworkStatus.isOnline(this)) {
        Handler().postDelayed({ mWebView.loadUrl(url) }, 400)
    } else {
        util.showToast(this, getString(R.string.no_internet), true)
    }
}

internal inner class MyWebChromeClient : WebChromeClient() {
    // For 3.0+ Devices (Start)
    // onActivityResult attached before constructor
    protected fun openFileChooser(uploadMsg: ValueCallback<*>, acceptType: String) {
        mUploadMessage = uploadMsg
        val i = Intent(Intent.ACTION_GET_CONTENT)
        i.addCategory(Intent.CATEGORY_OPENABLE)
        i.type = "image/*"
        startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE)
    }

    // For Lollipop 5.0+ Devices
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onShowFileChooser(mWebView: WebView, filePathCallback: ValueCallback<Array<Uri>>, fileChooserParams: FileChooserParams): Boolean {
        if (uploadMessage != null) {
            uploadMessage!!.onReceiveValue(null)
            uploadMessage = null
        }

        uploadMessage = filePathCallback

        val intent = fileChooserParams.createIntent()
        try {
            startActivityForResult(intent, REQUEST_SELECT_FILE)
        } catch (e: Exception) {
            uploadMessage = null
            util.showToast(this@WebLink, "Cannot Open File Chooser")
            return false
        }

        return true
    }

    //For Android 4.1 only
    protected fun openFileChooser(uploadMsg: ValueCallback<Uri>, acceptType: String, capture: String) {
        mUploadMessage = uploadMsg
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        intent.type = "image/*"
        startActivityForResult(Intent.createChooser(intent, "File Chooser"), FILECHOOSER_RESULTCODE)
    }

    protected fun openFileChooser(uploadMsg: ValueCallback<Uri>) {
        mUploadMessage = uploadMsg
        val i = Intent(Intent.ACTION_GET_CONTENT)
        i.addCategory(Intent.CATEGORY_OPENABLE)
        i.type = "image/*"
        startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE)
    }
}
 类似资料:
  • 我想使用FormData将图像上传到我的后端,但由于Ionic DEVAPP和Ionic VIEW不支持文件、文件传输和文件上传插件,我只需要使用Angular Http或HttpClient即可。 当使用DestinationType.FILE_URI时,我可以从文件中获取内部url并将其显示在img对象上,但如果没有本机文件、文件路径和文件传输插件,我无法从该url创建打字脚本文件对象。 }

  • 本文向大家介绍PHP实现文件上传和多文件上传,包括了PHP实现文件上传和多文件上传的使用技巧和注意事项,需要的朋友参考一下 在PHP程序开发中,文件上传是一个使用非常普遍的功能,也是PHP程序员的必备技能之一。值得高兴的是,在PHP中实现文件上传功能要比在Java、C#等语言中简单得多。下面我们结合具体的代码实例来详细介绍如何通过PHP实现文件上传和多文件上传功能。 要使用PHP实现文件上传功能,

  • 问题内容: 看来我还没有清楚地传达出我的问题。我需要发送一个文件(使用AJAX),并且需要使用Nginx HttpUploadProgressModule 获取文件的上传进度。我需要一个很好的解决方案。我已经尝试过使用jquery.uploadprogress插件,但是我发现自己不得不重写其中的大部分内容,以使其在所有浏览器中都能正常工作并使用AJAX发送文件。 我所需要的只是执行此操作的代码,它

  • 我对DDD和CQRS的概念是新的,无法找到一个最终的解决方案如何以一种干净的方式上传图像或文件。 我有三个想法来解决这个问题,但我对它们不是很满意。 方式1: 1。在单个请求中发布所有数据,包括图像(多部分) 2。创建,它返回. 3。之后,创建并将与构造函数中的根数据一起传递。就CQRS而言,一个用户交互应该只有一个命令。 方法2: 1。将图像发送到分离endpoint,创建临时文件并返回id或文

  • 我需要存储从照相机到gallery再到firebase的图像。在我的项目上传从画廊工作,但当我试图从相机上传什么都没有发生。当您在“多媒体资料”或“照相机”之间选择“单击”按钮时。当从“多媒体资料”中拍照或选择“图像”时,在“图像视图”中我可以获得图像。然后我点击save,若图片来自gallery,则保存到存储器,并在数据库中创建子对象,但若图片来自camera,则无法工作。这个问题有解决办法吗?

  • 本文向大家介绍详解SpringBoot文件上传下载和多文件上传(图文),包括了详解SpringBoot文件上传下载和多文件上传(图文)的使用技巧和注意事项,需要的朋友参考一下 最近在学习SpringBoot,以下是最近学习整理的实现文件上传下载的Java代码: 1、开发环境: IDEA15+ Maven+JDK1.8 2、新建一个maven工程:   3、工程框架   4、pom.xml文件依赖项