文件上传在Android WebView中不起作用

时间:2018-05-22 09:11:20

标签: android webview

对我来说,文件上传不适用于Android WebView。我已尝试在Android KitKat,Lollipop和更新版本上进行测试,但它仍无效。

这是我的代码:

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {
    private WebView myWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myWebView = (WebView)findViewById(R.id.webView);
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        myWebView.loadUrl("your domain url");
        myWebView.setWebViewClient(new WebViewClient());

    }

    @Override
    public void onBackPressed() {
        if(myWebView.canGoBack()){
            myWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

2 个答案:

答案 0 :(得分:1)

这里已经回答: File Upload in WebView

您还可以使用此网页浏览: https://github.com/mgks/Android-SmartWebView

答案 1 :(得分:0)

This是唯一为我工作的人

这是相同的Kotlin代码。

  

变量声明:

private var mUploadMessage:ValueCallback<Uri>? = null

var uploadMessage:ValueCallback<Array<Uri>>? = null

val REQUEST_SELECT_FILE = 100
  

将此webchromeclient设置为您的webview

    webViewMainActivity?.webChromeClient = object:WebChromeClient() {

        override fun onJsAlert(view: WebView, url: String, message: String, result: JsResult): Boolean {
            Log.d("alert", message)
            val dialogBuilder = AlertDialog.Builder(this@MainActivity)

            dialogBuilder.setMessage(message)
                .setCancelable(false)
                .setPositiveButton("OK") { _, _ ->
                    result.confirm()
                }

            val alert = dialogBuilder.create()
            alert.show()

            return true
        }

        // 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)
        }
    }
  

onActivity结果代码-

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

    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)
    }


}