MCDonald Blog

想写点东西

Android WebView上传文件

需要的变量

private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE = 1;
private final static int CAMERA_RESULTCODE = 2;
private Uri outputFileUri;

在WebChromeClient里添加

public void openFileChooser( ValueCallback<Uri> uploadMsg, String acceptType ) {  
    mUploadMessage = uploadMsg;  
    QYWebView.this.openImageIntent();
}   

// For Android < 3.0
public void openFileChooser( ValueCallback<Uri> uploadMsg ) {
    openFileChooser( uploadMsg, "" );
}

// For Android > 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
    openFileChooser( uploadMsg, "" );
}

onActivityResult处理

if(requestCode==FILECHOOSER_RESULTCODE)  {  
    if (null == mUploadMessage) return;  
    Uri result = intent == null || resultCode != RESULT_OK ? null: intent.getData();  
    mUploadMessage.onReceiveValue(result);  
    mUploadMessage = null;  
}  
if(requestCode==CAMERA_RESULTCODE) {  
    if (null == mUploadMessage) return;  
    outputFileUri = outputFileUri == null || resultCode != RESULT_OK ? null: outputFileUri;  
    mUploadMessage.onReceiveValue(outputFileUri);  
    mUploadMessage = null;  
}

体验

在我看来这样的上传方式用户体验相当不友好,特别是在上传图片时,如果图片比较大并且web前端没有进行压缩的话,那么上传速度达到龟速甚至上传失败,可想而之用户对此的烦躁心情,对你的产品大打折扣了。

我的建议还是上传文件模块还是使用native,本地压缩后上传。

ps:有草稿箱的设计更好!!