2015-02-24 48 views
6
Min SDK API 15 

你好,使用网页视图来浏览照片库

我使用上有一个按钮,将浏览应用图库网页视图。

但是,当在webview中点击按钮时,什么都不会发生。

URL是以下格式:

https://www.xxxxxxxxxxx 

我已经添加下列权限:

<uses-permission android:name="android.permission.INTERNET"/> 
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS" /> 
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
<uses-feature android:name="android.hardware.camera" android:required="false" /> 

我有将加载网页视图在onCreateView方法的片段(仅片段)与已启用javascript。

if(!message.isEmpty()) {    
    WebView webView = (WebView)view.findViewById(R.id.webview); 
    webView.getSettings().setJavaScriptEnabled(true); 
    webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); 
    webView.setWebViewClient(new WebViewClient()); 
    webView.loadUrl(message); 
} 

我创建了一个简单的HTML页面进行测试:

<!doctype html> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>Test Android Popup</title> 
</head> 
<body> 
<label>Test Alert 1:</label> 
<button type="button" onClick="alert('Test Alert Box1');">Click Me!</button> 
<br> 
<label>Test Browse file</label> 
<input type="file" name="img"> 
</body> 
</html> 

所以URL将被加载到web视图。网页视图显示一个按钮,用户将点击按钮浏览他们的画廊中的照片。

的网页流量看起来是这样的:当我点击他们 enter image description here

按钮无工作。

非常感谢您的任何建议,

这段代码适用于< 4.3。但是,4.4和5.0失败。

webView.setWebChromeClient(new WebChromeClient() { 
      /* Open File */ 
      public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) { 
       mImageFilePath = uploadMsg; 

       Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
       intent.addCategory(Intent.CATEGORY_OPENABLE); 
       intent.setType("image/*"); 

       startActivityForResult(intent, FILECHOOSER_RESULTCODE); 
      } 


      public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) { 
       mImageFilePath = uploadMsg; 

       Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
       intent.addCategory(Intent.CATEGORY_OPENABLE); 
       intent.setType("image/*"); 

       startActivityForResult(intent, FILECHOOSER_RESULTCODE); 
      } 

     }); 
+0

Whats your message String?你有https://吗?只有www。不起作用... Ups对不起,误读问题 – 2015-02-24 06:00:51

+0

我刚刚更新了我的答案与uri的格式。 – ant2009 2015-02-24 08:43:58

+0

我认为你已经更新了你的问题...... – 2015-02-24 09:42:41

回答

7

创建该文件,并将其放置在您的资产文件夹:webdemo.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
<title>title</title> 
</head> 
<body> 
<h1>Web View Demo</h1> 
<br> 
    <input type="button" value="Say hello" 
     onClick="showAndroidToast('Hello Android!')" /> 
    <br /> 
    File Uri: <label id="lbluri">no file uri</label> 
    <br /> 
    File Path: <label id="lblpath">no file path</label> 
    <br /> 
    <input type="button" value="Choose Photo" onClick="choosePhoto()" /> 
    <script type="text/javascript"> 
     function showAndroidToast(toast) { 
      Android.showToast(toast); 
     } 
     function setFilePath(file) { 
      document.getElementById('lblpath').innerHTML = file; 
      Android.showToast(file); 
     } 
     function setFileUri(uri) { 
      document.getElementById('lbluri').innerHTML = uri; 
      Android.showToast(uri); 
     } 
     function choosePhoto() { 
      var file = Android.choosePhoto(); 
      window.alert("file = " + file); 
     } 
    </script> 
</body> 
</html> 

集中在这里写的JavaScript。

写如下的活动: WebViewDemo.java

public class WebViewDemo extends Activity 
{ 

    private WebView webView; 

    final int SELECT_PHOTO = 1; 

    @SuppressLint("SetJavaScriptEnabled") 
    public void onCreate(Bundle savedInstanceState) 
    { 

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

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

     webView.getSettings().setJavaScriptEnabled(true); 

     webView.getSettings().setLoadWithOverviewMode(true); 

     // Other webview settings 
     webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); 
     webView.setScrollbarFadingEnabled(false); 
     webView.getSettings().setBuiltInZoomControls(true); 
     webView.getSettings().setPluginState(PluginState.ON); 
     webView.getSettings().setAllowFileAccess(true); 
     webView.getSettings().setSupportZoom(true); 
     webView.addJavascriptInterface(new MyJavascriptInterface(this), "Android"); 

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

    } 

    class MyJavascriptInterface 
    { 

     Context mContext; 

     /** Instantiate the interface and set the context */ 
     MyJavascriptInterface(Context c) 
     { 
      mContext = c; 
     } 

     /** Show a toast from the web page */ 
     @JavascriptInterface 
     public void showToast(String toast) 
     { 
      Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show(); 
     } 

     @JavascriptInterface 
     public String choosePhoto() 
     { 
      // TODO Auto-generated method stub 
      String file = "test"; 
      Intent photoPickerIntent = new Intent(Intent.ACTION_PICK); 
      photoPickerIntent.setType("image/*"); 
      startActivityForResult(photoPickerIntent, SELECT_PHOTO); 
      return file; 
     } 

    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) 
    { 
     switch (requestCode) 
     { 
     case SELECT_PHOTO: 
      if (resultCode == RESULT_OK) 
      { 
       Uri selectedImage = intent.getData(); 
       webView.loadUrl("javascript:setFileUri('" + selectedImage.toString() + "')"); 
       String path = getRealPathFromURI(this, selectedImage); 
       webView.loadUrl("javascript:setFilePath('" + path + "')"); 
      } 
     } 

    } 

    public String getRealPathFromURI(Context context, Uri contentUri) 
    { 
     Cursor cursor = null; 
     try 
     { 
      String[] proj = { MediaStore.Images.Media.DATA }; 
      cursor = context.getContentResolver().query(contentUri, proj, null, null, null); 
      int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
      cursor.moveToFirst(); 
      return cursor.getString(column_index); 
     } 
     finally 
     { 
      if (cursor != null) 
      { 
       cursor.close(); 
      } 
     } 
    } 

} 

使用此代码段,看看它是否工作。

以下截图取自Android 4.4 Kitkat设备。

see this screen shot

我不知道这是否解决方案的工作,你与否。这可能只是您的解决方法或突破。我希望它的某些部分会有所帮助。

+0

谢谢,Amrut。我会试试这个。但是,我注意到你正在使用JavaScript的接口。没有这个可以做到这一点吗? – ant2009 2015-02-26 10:17:08

+1

根据您的问题/要求,无法根据我的知识使用界面来解决问题。 – 2015-02-26 10:37:27

+0

谢谢,这解决了我的完整问题。 – ant2009 2015-03-06 04:36:01

2

那么你可以实现像这样

webView.setWebViewClient(new WebViewClient() { 


     @Override 
     public boolean shouldOverrideUrlLoading(WebView view, String url) { 
      if (url.equals("alert://alert")) { 
       Toast.makeText(this, "alert", Toast.LENGTH_LONG).show(); 
      } else if (url.equals("choose://image")) { 
       Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
       intent.addCategory(Intent.CATEGORY_OPENABLE); 
       intent.setType("image/*"); 

       startActivityForResult(intent, FILECHOOSER_RESULTCODE); 
      } 
      return true; 
     } 
    }); 

,你的HTML应该是这样的

<!doctype html> 
<html> 
    <head> 
    <meta charset="utf-8"> 
    <title>Test Android Popup</title> 
    </head> 
    <body> 
     <label>Test Alert 1:</label> 
     <form action="alert://alert"> 
      <input type="submit" value="Click me!"> 
     </form> 
     <br> 
     <label>Test Browse file</label> 
     <form action="image://choose"> 
      <input type="submit" value="Choose File"> 
     </form> 
    </body> 
</html> 
5

不幸的是,用户Slartibartfast在评论你的问题,输入型的人回答说“文件“在4.4设备上不起作用。谷歌代码上有一个issue,指出这是一个预期的行为(状态:WorkingAsIntended)。

即使如此,您提供的代码也适用于4.4.4(在Nexus 7平板电脑上测试过)和4.4.0版本的操作系统。

在5.0上,他们添加了记录的method来执行此操作。我使用下面的代码:

mWebView.setWebChromeClient(new WebChromeClient() { 
    // For Android < 3.0 - undocumented method 
    @SuppressWarnings("unused") 
    public void openFileChooser(ValueCallback<Uri> uploadMsg) { 
     openFileChooser(uploadMsg, ""); 
    } 

    // For Android 3.0+ - undocumented method 
    public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {     
     mUploadCallback = uploadMsg; 
     openFileChooserActivity(); 
    } 

    // For Android > 4.1 - undocumented method 
    @SuppressWarnings("unused") 
    public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){ 
     openFileChooser(uploadMsg, ""); 
    } 

    // For Android > 5.0 
    public boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) { 
     mUploadCallbackLollipop = filePathCallback; 
     openFileChooserActivity(); 
     return true; 
    } 
}); 

注意到关于改变的回调参数> 5.0:从ValueCallback<Uri>ValueCallback<Uri[]>

因此,对于> = 4.4和< 4.4.4,您应该实现自己的文件上传机制。一些建议:

  • 检查与JavaScript的Android操作系统版本,并提供一个<input type="file">它的工作原理。在4.4版本中,使用自己的url模式创建一个html元素(如Sushant说的,例如<form action="image://choose">)。然后,您可以在shouldOverrideUrlLoading中捕获它,并使用文件路径从java中调用JavaScript函数,但是无法访问文件的内容。对于小文件,您可以将base64文件内容作为参数传递给您的javascript函数,但对于较大的文件,您肯定会得到OutOfMemory异常。
  • 您可以执行上述步骤,但在Java中处理文件上传并仅提供javascript函数的路径。提交按钮可以利用Amrut Bidri所说的触发你在java中上传的内容。

所以,作为一个结论,我看到4.4和4.4.4之间OS版本两种选择:要么使用JavaScript来上传文件(内存问题),或者直接上传到java和实现你自己的沟通机制,你的应用程序和web视图。对于他们来说,你都需要访问你在webview中加载的网页。

我使用的JavaScript上传方法,因为我们使用的小文件,这是一个快一点来实现:

public boolean shouldOverrideUrlLoading(WebView view, String url) {   
    ... else if (url.startsWith(UPLOAD_FILE_URL_PREFIX)) { 
     openFileChooserActivity(); 
     return true; 
    } 

    return false; 
} 

上的活动结果,我做这样的事情了4.4版本(JavaScript函数insertFileForUpload处理文件上传):

private void invokeJavascriptWithFileContent(Uri fileUri) { 
    String fileContentInBase64 = readAndConvertFileToBase64(fileUri); 

    if (!fileContentInBase64.isEmpty()) { 
     String fileMimeType = getMimeType(activity, fileUri); 
     String fileName = getFileName(activity, fileUri); 

     // invoke javascript 
     String js = String.format("javascript:insertFileForUpload(\"%s\",\"%s\",\"%s\")", 
       fileName, 
       fileMimeType, 
       fileContentInBase64 
       ); 
     mWebView.loadUrl(js); 
    } 
} 

public static String getMimeType(Context context, Uri fileUri)  
{ 
    ContentResolver cR = context.getContentResolver(); 
    MimeTypeMap mime = MimeTypeMap.getSingleton(); 
    String type = mime.getExtensionFromMimeType(cR.getType(fileUri)); 

    return type; 
} 

此外,关于https://github.com/delight-im/Android-AdvancedWebView,似乎文件上传作品,但他们说:“文件上传自动处理(查询与AdvancedWebView.isFileUploadAvailable())”和“isFileUploadAvailable”包含以下代码:

/** 
* Returns whether file uploads can be used on the current device (generally all platform versions except for 4.4) 
* 
* @return whether file uploads can be used 
*/ 
public static boolean isFileUploadAvailable() { 
    return isFileUploadAvailable(false); 
} 

/** 
* Returns whether file uploads can be used on the current device (generally all platform versions except for 4.4) 
* 
* On Android 4.4.3/4.4.4, file uploads may be possible but will come with a wrong MIME type 
* 
* @param needsCorrectMimeType whether a correct MIME type is required for file uploads or `application/octet-stream` is acceptable 
* @return whether file uploads can be used 
*/ 
public static boolean isFileUploadAvailable(final boolean needsCorrectMimeType) { 
    if (Build.VERSION.SDK_INT == 19) { 
     final String platformVersion = (Build.VERSION.RELEASE == null) ? "" : Build.VERSION.RELEASE; 

     return !needsCorrectMimeType && (platformVersion.startsWith("4.4.3") || platformVersion.startsWith("4.4.4")); 
    } 
    else { 
     return true; 
    } 
} 

所以,你可能只是与正常的WebView同样的问题,但我还没有测试库,所以我真的不能说。

我可能已经创建了一个答案混乱,但我希望你能找到有用的东西。

+0

感谢您的回答。 – ant2009 2015-03-05 04:17:57

0

通过此代码可以采取移动文件的路径,只有我不能上传文件在PHP中。以下是我使用的php代码:

$arquivo = $_POST['lblpath']; 

$url = "file:///storage/external_SD/fotos/IMG10022.jpg"; //url da imagem que venha de um textField 

//PEGA INFORMAÇÕES DA IMAGEM 
$file_info = getimagesize($url);  


//VERIFICA EXTENSÃO DA IMAGEM 
if ($file_info['mime'] == "image/jpeg") 
$img = imagecreatefromjpeg($url); 
else if ($file_info['mime'] == "image/gif") 
$img = imagecreatefromgif($url); 
else if ($file_info['mime'] == "image/png") 
$img = imagecreatefrompng($url); 

$altura = $file_info[1]; 

//PASSA AS MEDIDAS PARA A IMAGEM 
$x = imagesx($img); 
$y = imagesy($img); 
$largura = ($altura * $x)/$y; 


//CRIA A IMAGEM 
$nova = imagecreatetruecolor($largura, $altura); 
imagealphablending($nova, false); 
imagesavealpha($nova, true); 
imagecopyresampled($nova, $img, 0, 0, 0, 0, $largura, $altura, $x, $y); 


//NOME DA IMAGEM 
$imgName = end(explode("/", $url)); 

//LOCAL PARA SALVAR 
$pasta = "images/"; // defina sua path 
$local = $pasta . $imgName; 


//SALVA NOVA IMAGEM 
if ($file_info['mime'] == "image/jpeg") 
imagejpeg($nova, $local, 100); 
else if ($file_info['mime'] == "image/png") 
imagepng($nova, $local, 9); 

//DESTROI ELEMENTOS 
imagedestroy($img); 
imagedestroy($nova);