Android Webview 图片转Base64上传 - liziNo1/Android-webview-upload-image GitHub Wiki

项目中经常会遇到原生与h5页面混合开发,h5页面访问本地图片资源数据几乎是基本功能,js交互参数传递的常用方式如下:

1、无返回值 webView.loadUrl("javascript:callJS(parameter)")

2、可带返回值 webView.evaluateJavascript("javascript:callJS(parameter)", new ValueCallback() {

@Override public void onReceiveValue(String value) {

Log.i(LOGTAG, "onReceiveValue value=" + value); }});

以上两种方式如果字符串参数长度有限制,无法满足大图片base64上传

3、JS注入方式,h5页面获取转化好的字符串 webview.addJavascriptInterface(new WebAppInterface(), "Android");

class WebAppInterface {

@JavascriptInterface
public String imageData() {
    return imageData;

}

}

//直接文件流转Base64,不光可以支持图片类型转化,其他任意类型文件都可以采用此方式,亲测可传13M的大图片,更大的尚未试过,其他同学有机会可以试试,至少项目中还未碰到反馈大图片上传失败的

private String compressBitmap(String imagePath) {

File file = new File(imagePath);
FileInputStream inputFile = null;
try {
    inputFile = new FileInputStream(file);
    byte[] buffer = new byte[(int) file.length()];
    inputFile.read(buffer);
    inputFile.close();
    return Base64.encodeToString(buffer, Base64.DEFAULT);
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
return "";

}