通过Javascript从Android原生相机上传图像到服务器

时间:2017-01-09 09:14:47

标签: javascript android html webview

我的html页面jsfiddle

的小提琴

现在使用这个我可以在Android设备中打开本机相机。

但我无法保存图像,然后将此图像发送到服务器,以便我可以将其保存在我的数据库中。

从设备库中选择图像以在服务器上发送和保存图像后,我该怎么办?

打开使用的本机相机功能:

 function choosePhoto() {
        var file = Android.choosePhoto();
        window.alert("file = " + file);
    }

1 个答案:

答案 0 :(得分:0)

参考您提出的相关问题, 检查我的答案 https://stackoverflow.com/a/41570241/3518278

我的回答涵盖了如何打开相机并从设备中获取图像并将其设置为html。

这对你的场景有何帮助,你可以使用js / jQuery从视图中获取图像< IMG>并执行ajax / http请求将其发布/放入服务器。在你的情况下,你不需要< IMG>要设置图像,您可以将数据保存在变量中并直接将其发布到服务器或将图像设置为隐藏的< IMG>并继续。

因此,您将使用以下代码通过JSInterface

获取并将图像发送到html
                    // Get the image data in a byte array
                    File imageFile = new File(imagePath);
                    Bitmap bitmap = Util.convertImageFileToBitmap(imageFile.getAbsolutePath(), Constants.IMAGE_COMPRESSED_WIDTH, Constants.IMAGE_COMPRESSED_HEIGHT);
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
                    byte[] bytes = stream.toByteArray();

                    // get the base 64 string of the image which was converted to a byte array above
                    final String imgBase64String = Base64.encodeToString(bytes, Base64.NO_WRAP);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mWebView.loadUrl("javascript:imageData('" + imgBase64String + "')");
                        }
                    });

您的html将包含以下代码段

function imageData(data){
    document.getElementById('displayImage').setAttribute( 'src', 'data:image/png;base64,'+data );        
  }

可以在此处找到涵盖您正在寻找的功能的示例项目

https://drive.google.com/drive/folders/0BwRMp8dK9LMLeEo5cTlXVE9ZUW8?usp=sharing