【问题标题】:How to upload photo from library in webview in android app如何在android应用程序的webview中从库中上传照片
【发布时间】:2016-09-10 12:32:20
【问题描述】:

我在我的 android 应用程序上使用 webview 组件。用户可以从 android 照片库中加载图像,并在 webview 的网页上显示这些图像。如何从 javascript 将这些图像上传到我的后端服务器?

下面是我处理图像选择器行为的 java 代码:

setWebChromeClient(new WebChromeClient() {

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                Intent chooser = Intent.createChooser(intent, "Select Image");
                activity.startActivityForResult(chooser, ResultCode.CHOOSE_PHOTO_REQUEST);
                return false;
            }
        });

上面的代码将显示图像选择器,当用户选择图像时,onActivityResult 会将选择的图像路径传递给 javascript,如下所示:

       if (resultCode == Activity.RESULT_OK) {
            Uri imageUri = imageReturnedIntent.getData();
            Log.d("IMAGE", "choose image uri " + imageUri);
            String path = getRealPathFromURI(imageUri);
            Log.d("IMAGE", "choose image real path " + path);
            webView.loadUrl("javascript:choosePhotos('" + path + "')");
        }

      public String getRealPathFromURI(Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = {MediaStore.Images.Media.DATA};
            cursor = mainActivity.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();
            }
        }
    }

在 javascript 中,我可以将图像路径放在 &lt;img src=''/&gt; 标记上以显示所选图像。路径是这样的:'/storage/emulated/0/DCIM/Camera/IMG_20160808_200837.jpg'

在这里工作正常。但现在我想将此图像上传到我的后端服务器。 javascript如何处理这个路径:/storage/emulated/0/DCIM/Camera/IMG_20160808_200837.jpg。

【问题讨论】:

标签: javascript android image webview


【解决方案1】:

您可以使用 filePathCallback 将选定的文件传递给 webview。 只需创建一个全局变量

ValueCallback filePathCallback;

并将 onShowFileChooser() 方法中的参数分配给它。 然后您可以在 onActivityResult() 中使用此回调将所选文件传递给 webview:

Uri 结果[] = new Uri[]{imageUri};

filePathCallback.onReceiveValue(results);

然后在 html 上,您将在

处获得文件

【讨论】:

  • 我可以在 webview 中获取文件 uri。我的问题是如何从 webview 中的 javascript 将此文件上传到服务器。
  • 如果您在 html 中使用输入类型文件,例如表单中的 ,那么您可以简单地提交形式,这里 enctype 是 imp。您可以简单地从 ajax 上传表单。参考stackoverflow.com/a/22621393/1938011
猜你喜欢
  • 2022-11-18
  • 1970-01-01
  • 2019-04-03
  • 1970-01-01
  • 1970-01-01
  • 2017-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多