图片preVIEW Android中的WebView之前上传不工作 [英] Image preview in Android webview before upload not working

查看:152
本文介绍了图片preVIEW Android中的WebView之前上传不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以及我米做一个Android的WebView应用程序,即时通讯面临的一个问题在这里。 我米试图preVIEW我的形象在网页上上传之前 这是我的 HTML和Java脚本 codeIM使用。

 <!DOCTYPE HTML>
< HTML>
< HEAD>

&所述;脚本的src =htt​​p://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js>&所述; /脚本>


<脚本类型=文/ JavaScript的>

$(文件)。就绪(函数(){
    VAR preVIEW = $(upload- preVIEW IMG。);

    $(文件)。改变(函数(事件){
       变种输入= $(event.currentTarget);
       var文件=输入[0] .files [0];
       VAR读卡器=新的FileReader();
       reader.onload =功能(E){
           image_base64 = e.target.result;
           preview.attr(src用户,image_base64);
       };
       reader.readAsDataURL(文件);
    });
});

< / SCRIPT>

< /头>

<身体GT;
< D​​IV CLASS =upload- preVIEW>
    < IMG />
< / DIV>
<输入类=文件名称=标志类型=文件>

< /身体GT;
< / HTML>
 

这里是小提琴

它的工作就好了几乎所有的浏览器(如火狐,Chrome和IE)没有任何错误或警告。这里是火狐的快照(显示上传前的preVIEW)

现在,每当我尝试在机器人的WebView打开这个它没有显示图像preVIEW 它显示了这样的事情

我不知道什么是错,我已经启用的JavaScript 键,包括的jQuery 。它让我疯了,因为一天。

下面是我的Andr​​oid的WebView code。

 包net.kaosfield.wv1;

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

公共类MainActivity延伸活动{

活动活性= MainActivity.this;

私人的WebView web视图= NULL;

私人ValueCallback<乌里> uploadMessage;

私人最终静态INT FILECHOOSER_RESULT code = 1;

私有静态字符串registrationId =;

私人MyFunctions myFunctions;

@覆盖
保护无效onActivityResult(INT申请code,INT结果code,
        意向意图){
    如果(要求code == FILECHOOSER_RESULT code){
        如果(uploadMessage == NULL)
            返回;
        开放的结果=意图== NULL ||因此code!= RESULT_OK?空值
                :intent.getData();
        uploadMessage.onReceiveValue(结果);
        uploadMessage = NULL;
    }
}

@燮pressLint(SetJavaScriptEnabled)
@覆盖
保护无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);

    myFunctions =新MyFunctions(活动);

            web视图=(web视图)findViewById(R.id.webview);
    webView.setInitialScale(myFunctions.setWebViewScale());

    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(真正的);
    webView.setWebViewClient(新WebViewClient(){
        公共布尔shouldOverrideUrlLoading(web视图查看,字符串URL){
            如果(url.startsWith(net.kaosfield.wv1:)){
                Log.d(WV1,网址);
                返回true;
            }
            返回false;
        }

        @覆盖
        公共无效onPageFinished(web视图查看,字符串URL){
            Log.d(WV1,onPageFinished);
            String参数=d.e.f;
            view.loadUrl(JavaScript的:警报(window.method(\+说法
                    +\)));
        }
    });
    webView.setWebChromeClient(新WebChromeClient(){
        @覆盖
        公共布尔onJsAlert(web视图查看,URL字符串,字符串的消息,
                JsResult结果){
            如果(message.equals(net.kaosfield.wv1)){
                尝试 {
                    Log.d(WV1,URL:+网址+,留言:+消息);
                    返回true;
                } 最后 {
                    result.confirm(); //为了不发出警报
                }
            } 其他 {
                返回false;
            }
        }

        //为Android 3.0+
        @燮pressWarnings(未使用)
        公共无效openFileChooser(ValueCallback<乌里> uploadMsg){
            uploadMessage = uploadMsg;
            意图I =新的意图(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType(图像/ *);
            MainActivity.this.startActivityForResult(
                    Intent.createChooser(我,文件选择),
                    FILECHOOSER_RESULT code);
        }

        //为Android 3.0+
        @燮pressWarnings(未使用)
        公共无效openFileChooser(ValueCallback<乌里> uploadMsg,
                字符串acceptType){
            uploadMessage = uploadMsg;
            意图I =新的意图(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType(图像/ *);
            MainActivity.this.startActivityForResult(
                    Intent.createChooser(我,文件浏览器),
                    FILECHOOSER_RESULT code);
        }

        //为Android 4.1
        @燮pressWarnings(未使用)
        公共无效openFileChooser(ValueCallback<乌里> uploadMsg,
                字符串acceptType,字符串捕获){
            uploadMessage = uploadMsg;
            意图I =新的意图(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType(图像/ *);
            MainActivity.this.startActivityForResult(
                    Intent.createChooser(我,文件选择),
                    MainActivity.FILECHOOSER_RESULT code);
        }
    });

     webView.loadUrl(http://blue.genetechz.com/qadir/test.php);
}

@覆盖
公共布尔onCreateOptionsMenu(功能菜单){
    //充气菜单;这增加了项目操作栏,如果它是present。
    。getMenuInflater()膨胀(R.menu.main,菜单);
    返回true;
}

@覆盖
公共布尔的onkeydown(INT键code,KeyEvent的事件){
    //检查关键事件是后退按钮,如果有历史记录
    如果((钥匙code == KeyEvent.KEY code_BACK)及和放大器; webView.canGoBack()){
        webView.goBack();
        返回true;
    }
    //如果不是返回键或没有网页的历史,冒泡
    //到默认
    //系统行为(可能退出活动)
    返回super.onKeyDown(键code,事件);
}

}
 

解决方案

您必须做出这个改变对onActivityRestult因为网址从库返回不正确的:

  @覆盖
保护无效onActivityResult(INT申请code,INT结果code,
        意向意图){
    如果(要求code == FILECHOOSER_RESULT code){

        如果(uploadMessage == NULL)
            返回;

        开放的结果=意图== NULL ||因此code!= RESULT_OK?空值
                :intent.getData();
        如果(结果!= NULL){

            字符串文件路径= NULL;

            如果(内容.equals(result.getScheme())){

                光标光标= this.getContentResolver()查询(因此,新的String [] {} android.provider.MediaStore.Images.ImageColumns.DATA,NULL,NULL,NULL);
                    cursor.moveToFirst();
                    文件路径= cursor.getString(0);
                    cursor.close();

            } 其他 {

                文件路径= result.getPath();

            }

            乌里myUri = Uri.parse(文件路径);
            uploadMessage.onReceiveValue(myUri);

        } 其他 {

            uploadMessage.onReceiveValue(结果);

        }

        uploadMessage = NULL;
    }
}
 

现在它会返回一个URL与文件:即使您选择从图库中的图像/// 格式

well I m making an android webview app, Im facing an issue here. I m trying to preview my image on webpage before uploading Here is my html and java script code i m using.

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

here is fiddle

Its working just fine on almost every browser (i.e Firefox, Chrome and IE) without any error or warning. here is snapshot of firefox (showing the preview before upload)

Now whenever I try to open this in android webview its not showing the image preview it shows something like this

I don't know whats wrong, I have enable the javascript and included the jquery. Its driving me crazy since one day.

here is my android webview code.

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

}

解决方案

You have to make this changes on the onActivityRestult because the urls returned from the gallery aren't right:

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

Now it will return an url with the file:/// format even if you choose the image from the gallery.

这篇关于图片preVIEW Android中的WebView之前上传不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆