如何从webview上传图片?

时间:2015-12-18 11:01:37

标签: android android-webview

我的app(Android 4.4.4+)中嵌入了webview的问题。在页面上有一个我使用openFileChooser管理的“上传图片”按钮。

在某些设备上,当我点击网页视图中的“上传图片”按钮时,相机应用程序就会启动,我的应用程序也会被销毁。拍摄照片后,我的应用程序被重新创建,我恢复了webview状态(保存在onSaveInstanceState中)并调用了onActivityResult()。问题是包含mUploadMessage的变量ValueCallBack为空,因此我无法调用ValueCallBack.onReceiveValue()将图像URI提供给webview。

// openFileChooser for Android 3.0+ to 4.4
// WARNING: the openFileChooser works in version 4.4 only for 4.4.3+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
    // Update message
    mUploadMessage = uploadMsg;
    fileChooserManagement(FILECHOOSER_RESULTCODE);
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    webview.saveState(outState);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if (savedInstanceState != null) {
        // Restore last state
        webview.restoreState(savedInstanceState);
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Do not test the resultCode, because it's mandatory to enter the 'if' and to call the
    // onReceiveValue even with null. Otherwise the openFileChooser will not be called anymore.
    if (requestCode == FILECHOOSER_RESULTCODE) {
        if (this.mUploadMessage == null) {
            Log.i("myApp", "onActivityResult mUploadMessage is null");
            return;
        }
        mUploadMessage.onReceiveValue(processPicture(resultCode, data));
        mUploadMessage = null;
    }
}

有一个类似的话题here,但问题是“我不明白如何保存webview状态并恢复它。如果我在onRestoreInstanceState()中恢复它,页面不会从相机拍摄照片你能举个例子吗?“没有答案。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我知道您没有在代码的任何位置实现webview客户端。您需要实现webview并使用Web chrome客户端类来处理Android应用程序上的文件上载。此外,您应该覆盖网址加载。此外,您需要添加Internet访问权限和从外部存储读取的权限。您可以阅读更多内容并下载演示相同 here 的演示。我希望能帮助你