javascript - 上传前 Android webview 中的图像预览不起作用

标签 javascript android jquery android-webview

我正在制作一个 android webview 应用程序,我在这里面临一个问题。 我正在尝试在上传之前在网页上预览我的图像 这是我正在使用的 html 和 java script 代码。

<!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>

这里是fiddle

它在几乎所有浏览器(即 Firefox、Chrome 和 IE)上都能正常工作,没有任何错误或警告。这是 Firefox 的快照(显示上传前的预览) enter image description here

现在,每当我尝试在 android webview 中打开它时,它都不会显示图像预览 它显示类似这样的内容

enter image description here

我不知道出了什么问题,我已启用 javascript 并包含 jquery。从有一天起,它就让我发疯。

这是我的 android webview 代码。

package net.kaosfield.wv1;

import my.functions.MyFunctions;
import android.net.Uri;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebViewClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.JsResult;
import android.content.Intent;
import com.google.android.gcm.GCMRegistrar;

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 = "";

private MyFunctions myFunctions;

@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();
        uploadMessage.onReceiveValue(result);
        uploadMessage = null;
    }
}

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

    myFunctions = new MyFunctions(activity);

            webView = (WebView) findViewById(R.id.webview);
    webView.setInitialScale(myFunctions.setWebViewScale());

    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("http://blue.genetechz.com/qadir/test.php");
}

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

}

最佳答案

您必须在 onActivityRestult 上进行此更改,因为从库返回的网址不正确:

@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;
    }
}

现在,即使您从图库中选择图像,它也会返回一个 file:/// 格式的 URL。

关于javascript - 上传前 Android webview 中的图像预览不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19947559/

相关文章:

javascript - 停止特定处理程序的事件传播

jquery - 如何使按钮上添加的复选标记符号与其一起滚动?

单击时 jquery 更改样式(context = bootstrap)

php - 如何在一个页面上运行多个ajax调用

javascript - 如果浏览器关闭,则执行所有 ajax 请求

javascript - jquery或native无法通过ID获取元素

javascript - 按对象值排序不起作用?

Android - 如何为约束布局参数设置动画?

java - 单击后退按钮重定向到 Android 设备中的主窗口/屏幕

Android Lollipop DatePicker 无法正常工作