无法在android webview上运行show image preview?

时间:2014-06-24 07:37:55

标签: javascript android jsp webview

首先,这可能听起来像一个重复的问题,但我无法通过以前发布的问题获得任何解决方案。我有一个jsp页面,通过它我从PC中选择图像并显示该图像的预览在Chrome浏览器上工作正常我的Android手机也是。但是当我在WEBVIEW document.getElementById.click()上运行时功能不起作用,我无法进行图像预览。

这是我的JSP页面:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">    </script>
    <script>
        function img_prvw(id1,id2)/*******************show preview of  image*******************/
{

var oFiles = document.getElementById(id1).files;
var valid_extensions = /(.jpg|.jpeg|.png)$/i;
if(!(valid_extensions.test(document.getElementById(id1).files[0].name)))
{
document.getElementById('er').innerHTML="Select jpg or png image";
}
else
{
var reader = new FileReader();
reader.readAsDataURL(oFiles[0]);
reader.onload=
function (e) {
document.getElementById(id2).src=e.target.result;
};
}
}

        </script>
 </head>
 <body>
  <input type="file" style="display: none;" id="advrts_img" name="advrts_img" onchange="img_prvw('advrts_img','advrts_img_prvw')">
<img src="images/img_place.png" id="advrts_img_prvw" alt="" class="cursor margin_top10" style="width:100px;height:100px" onClick="document.getElementById('advrts_img').click()">
 </body>
 </html>

这是我的Android WebView代码:

package com.example.sample_webview;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class MainActivity extends Activity {
/** Called when the activity is first created. */

WebView web;

private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE = 1;

@Override
protected void onActivityResult(int requestCode, int resultCode,
        Intent intent) {
    if (requestCode == FILECHOOSER_RESULTCODE) {
        if (null == mUploadMessage)
            return;
        Uri result = intent == null || resultCode != RESULT_OK ? null
                : intent.getData();
        mUploadMessage.onReceiveValue(result);
        mUploadMessage = null;
    }
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    web = (WebView) findViewById(R.id.wView);

    web = new WebView(this);
    web.getSettings().setJavaScriptEnabled(true);
    web.loadUrl("http://minkme.org/minkmeuser/image_preview1.jsp");
    web.setWebViewClient(new myWebClient());
    web.setWebChromeClient(new WebChromeClient() {
        // The undocumented magic method override
        // Eclipse will swear at you if you try to put @Override here
        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {

            mUploadMessage = 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+
        public void openFileChooser(ValueCallback uploadMsg,
                String acceptType) {
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            MainActivity.this.startActivityForResult(
                    Intent.createChooser(i, "File Browser"),
                    FILECHOOSER_RESULTCODE);
        }

        // For Android 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg,
                String acceptType, String capture) {
            mUploadMessage = 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);

        }

    });

    setContentView(web);

}

public class myWebClient extends WebViewClient {
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        // TODO Auto-generated method stub
        super.onPageStarted(view, url, favicon);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // TODO Auto-generated method stub

        view.loadUrl(url);
        return true;

    }

    @Override
    public void onPageFinished(WebView view, String url) {
        // TODO Auto-generated method stub
        super.onPageFinished(view, url);

    }
}

// flipscreen not loading again
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
}

// To handle "Back" key press event for WebView to go back to previous
// screen.
/*
 * @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if
 * ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) { web.goBack();
 * return true; } return super.onKeyDown(keyCode, event); }
 */
     }

我只想使用输入类型=“文件”浏览Android手机中的图像。

1 个答案:

答案 0 :(得分:1)

简而言之:请查看输入文件Input file in a webview

经过一段时间和一些测试,我发现document.getElementById.click工作得很好。我测试了以下更改

<强> 的test.html

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
    <script src="jquery-1.11.1.min.js">    </script>
    <script>

        function img_prvw(id1,id2)/*******************show preview of  image*******************/
        {
            console.log("Call of img_prvw");
            var oFiles = document.getElementById(id1).files;
            var valid_extensions = /(.jpg|.jpeg|.png)$/i;
            if(!(valid_extensions.test(document.getElementById(id1).files[0].name)))
            {
                document.getElementById('er').innerHTML="Select jpg or png image";
            }
            else
            {
                var reader = new FileReader();
                reader.readAsDataURL(oFiles[0]);
                reader.onload=
                        function (e) {
                            document.getElementById(id2).src=e.target.result;
                        };
            }
        }

        function onAdvrtsImgPrvwClick() {
            console.log('Clickevent');
            document.getElementById('advrts_img').click();
        }

    </script>
</head>
<body>
<input type="file" style="display: none;" id="advrts_img" name="advrts_img" onclick="console.log('click on input');" onchange="img_prvw('advrts_img','advrts_img_prvw')">
<img src="images/img_place.png" id="advrts_img_prvw" alt="" class="cursor margin_top10" style="width:100px;height:100px" onClick="onAdvrtsImgPrvwClick()">
</body>
</html>

<强> MainActivity.java

public class MainActivity extends Activity {

private WebView mWebview;
static final String TAG = "MainActivity";

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mWebview = (WebView) findViewById(R.id.webView1);

    mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript

    final Activity activity = this;

    mWebview.setWebViewClient(new WebViewClient() {
        public void onReceivedError(WebView view, int errorCode,
                String description, String failingUrl) {
            Toast.makeText(activity, description, Toast.LENGTH_SHORT)
                    .show();
        }
    });

    mWebview.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onConsoleMessage(ConsoleMessage cm)
        {
            String msg = cm.message() + " -- From line " + cm.lineNumber() + " of " + cm.sourceId();
            switch (cm.messageLevel()) {
                case ERROR:
                    Log.e(TAG, msg);
                    break;
                case LOG:
                case TIP:
                    Log.i(TAG, msg);
                    break;
                case WARNING:
                    Log.w(TAG, msg);
                    break;
                case DEBUG:
                default:
                    Log.d(TAG, msg);
                    break;
            }

            return true;
        }
    });


    mWebview.loadUrl("file:///android_asset/test.html");
    //setContentView(mWebview);

}
}

并且显示控制台显示消息&#39;点击输入&#39;,因此它已被正确调用,但它是未正确调用的on更改。< / p>