Android WebView中上传文件的问题,通常出现在选择文件后无法将文件正确地上传到服务器。为了解决这个问题,需要在WebView中加入自定义的FileChooser,以便正确地处理文件上传过程。
以下是一个代码示例:
在Activity中,添加以下代码:
private static final int FILE_CHOOSER_RESULT_CODE = 1;
private ValueCallback mFilePathCallback;
private String mCameraPhotoPath;
// For Android 4.1+
public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg, acceptType);
}
// For Android 4.0-
public void openFileChooser(ValueCallback uploadMsg) {
openFileChooser(uploadMsg, "");
}
// For Android 3.x
public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
mFilePathCallback = new ValueCallback() {
@Override
public void onReceiveValue(Uri[] uris) {
mFilePathCallback = null;
if (uris == null || uris.length == 0) {
return;
}
String filePath = GetFilePathFromUri.getPath(getApplicationContext(), uris[0]);
if (!TextUtils.isEmpty(filePath)) {
Uri uri = Uri.fromFile(new File(filePath));
uploadFiles(new Uri[]{uri});
} else {
// Handle Error
}
}
};
Intent chooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
chooserIntent.setType(acceptType);
startActivityForResult(chooserIntent, FILE_CHOOSER_RESULT_CODE);
}
// For Android 5.0+
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, FileChooserParams fileChooserParams) {
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePathCallback;
Intent intent = fileChooserParams.createIntent();
try {
startActivityForResult(intent, FILE_CHOOSER_RESULT_CODE);
} catch (ActivityNotFoundException e) {
mFilePathCallback = null;
return false;
}
return true;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {