- 在AndroidManifest.xml文件中添加权限
- 在WebViewClient中使用onShowFileChooser()方法接收上传请求
private ValueCallback mUploadMessage;
private static final int REQUEST_SELECT_FILE = 100;
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
if (mUploadMessage != null) {
mUploadMessage.onReceiveValue(null);
}
mUploadMessage = filePathCallback;
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(webView.getContext().getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
}
if (photoFile != null) {
mCapturedImageUri = FileProvider.getUriForFile(webView.getContext(), webView.getContext().getApplicationContext().getPackageName() + ".provider", photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageUri);
} else {
intent = null;
}
}
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
if (intent != null) {
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{intent});
}
startActivityForResult(chooserIntent, REQUEST_SELECT_FILE);
return true;
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = webView.getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
mCameraImagePath = "file:" + image.getAbsolutePath();
return image;
}
- 在