Image preview in Android WebView only shows the image name

风流意气都作罢 提交于 2020-02-02 13:55:21

问题


I have a very small requirement.I want to show a image in the WebView from gallery.But after browsing from gallery, it only renders the image name instead of showing the image.I referred this post. Below are html and java script code,

<!DOCTYPE html>
<html>
<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>


<script type="text/javascript">

$(document).ready(function(){
    var preview = $(".upload-preview img");

    $(".file").change(function(event){
       var input = $(event.currentTarget);
       var file = input[0].files[0];
       var reader = new FileReader();
       reader.onload = function(e){
           image_base64 = e.target.result;
           preview.attr("src", image_base64);
       };
       reader.readAsDataURL(file);
    });
});

</script>

</head>

<body>
<div class="upload-preview">
    <img />
</div>
<input class="file" name="logo" type="file">

</body>
</html>

and below is the Android code,

 public class MainActivity extends Activity {

        Activity activity = MainActivity.this;

        private WebView webView = null;

        private ValueCallback<Uri> uploadMessage;

        private final static int FILECHOOSER_RESULTCODE = 1;

        private static String registrationId = "";


 @Override
protected void onActivityResult(int requestCode, int resultCode,Intent intent) {
    if (requestCode == FILECHOOSER_RESULTCODE) {

        if (uploadMessage == null)
            return;

        Uri result = intent == null || resultCode != RESULT_OK ? null
                : intent.getData();
        if (result!=null){

            String filePath = null;

            if ("content".equals(result.getScheme())) {

                Cursor cursor = this.getContentResolver().query(result, new String[] {    android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
                    cursor.moveToFirst();   
                    filePath = cursor.getString(0);
                    cursor.close();

            } else {

                filePath = result.getPath();

            }

            Uri myUri = Uri.parse(filePath);
            uploadMessage.onReceiveValue(myUri);

        } else {

            uploadMessage.onReceiveValue(result);

        }

        uploadMessage = null;
    }
}

        @SuppressLint("SetJavaScriptEnabled")
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);


            webView = (WebView) findViewById(R.id.Web);

            WebSettings webSettings = webView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webView.setWebViewClient(new WebViewClient() {
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    if (url.startsWith("net.kaosfield.wv1:")) {
                        Log.d("wv1", url);
                        return true;
                    }
                    return false;
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    Log.d("wv1", "onPageFinished");
                    String argument = "d.e.f";
                    view.loadUrl("javascript:alert(window.method(\"" + argument
                            + "\"))");
                }
            });
            webView.setWebChromeClient(new WebChromeClient() {
                @Override
                public boolean onJsAlert(WebView view, String url, String message,
                        JsResult result) {
                    if (message.equals("net.kaosfield.wv1")) {
                        try {
                            Log.d("wv1", "url: " + url + ", message: " + message);
                            return true;
                        } finally {
                            result.confirm(); // in order not to alert
                        }
                    } else {
                        return false;
                    }
                }

                // For Android 3.0+
                @SuppressWarnings("unused")
                public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                    uploadMessage = uploadMsg;
                    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                    i.addCategory(Intent.CATEGORY_OPENABLE);
                    i.setType("image/*");
                    MainActivity.this.startActivityForResult(
                            Intent.createChooser(i, "File Chooser"),
                            FILECHOOSER_RESULTCODE);
                }

                // For Android 3.0+
                @SuppressWarnings("unused")
                public void openFileChooser(ValueCallback<Uri> uploadMsg,
                        String acceptType) {
                    uploadMessage = uploadMsg;
                    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                    i.addCategory(Intent.CATEGORY_OPENABLE);
                    i.setType("image/*");
                    MainActivity.this.startActivityForResult(
                            Intent.createChooser(i, "File Browser"),
                            FILECHOOSER_RESULTCODE);
                }

                // For Android 4.1
                @SuppressWarnings("unused")
                public void openFileChooser(ValueCallback<Uri> uploadMsg,
                        String acceptType, String capture) {
                    uploadMessage = uploadMsg;
                    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                    i.addCategory(Intent.CATEGORY_OPENABLE);
                    i.setType("image/*");
                    MainActivity.this.startActivityForResult(
                            Intent.createChooser(i, "File Chooser"),
                            MainActivity.FILECHOOSER_RESULTCODE);
                }
            });

            webView.loadUrl("file:///android_asset/abc.html");
        }

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

        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            // Check if the key event was the Back button and if there's history
            if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
                webView.goBack();
                return true;
            }
            // If it wasn't the Back key or there's no web page history, bubble up
            // to the default
            // system behavior (probably exit the activity)
            return super.onKeyDown(keyCode, event);
        }

    }

but after picking a image from gallery, it only shows the image name.Below is the screen shot. Could anyone tell me whats wrong here?Any help will be appreciated.

来源:https://stackoverflow.com/questions/21040284/image-preview-in-android-webview-only-shows-the-image-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!