此应用程序中的WebView会打开一个带有上载按钮的页面。
下面是一个代码块,可以打开一个对话框从gallery或camera上传图像。
在我的活动中,我有:
private WebView wv;
//make HTML upload button work in Webview
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE=1;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode==FILECHOOSER_RESULTCODE)
{
if (null == mUploadMessage) return;
Uri result = intent == null || resultCode != RESULT_OK ? null
: intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
在onCreate中,我有以下内容:
wv.setWebChromeClient(new WebChromeClient() {
private Uri imageUri;
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType ) {
File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyApp");
// Create the storage directory if it does not exist
if (! imageStorageDir.exists()){
imageStorageDir.mkdirs();
}
File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
imageUri = Uri.fromFile(file);
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for(ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent i = new Intent(captureIntent);
i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
i.setPackage(packageName);
i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
cameraIntents.add(i);
}
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
Intent chooserIntent = Intent.createChooser(i,"Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
MainActivity.this.startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
文件浏览器和图库正在按预期工作。问题是,当我用相机拍照时,它没有上载到“选择文件”选项中,该选项显示状态“未选择文件”。
选择相机时:
使用相机拍摄快照:出现返回和检查选项。
关于选择检查标记:
文件未上传:(在“选择文件”选项中)
预期:
我检查了我是否有适当的写作权限,因此生成了一个名为“MyApp”的目录,并将图片存储在其中(如果在点击网页上的上传按钮后调用相机拍摄)。
在点击复选标记后,如何通过编程告诉应用程序选择从相机(存储在MyApp目录中)拍摄的照片?
更新6/18:这似乎不适用于Android4.2.1的三星银河S2。这在4.1.2的HTC One X上运行良好。请注意。
我也遇到了同样的问题。问题是这样的,我是如何解决的。
问题:
当openFileChooser
被调用时,回调对象ValueCallback
修正:
修复包括执行一些javascript,所以在webview上启用javascript。基本上,如果我们丢失了前一个对象,我们会得到另一个回调对象。
我们需要创建一个布尔字段“
mUploadFileOnLoad
”和三个字段。
private int mReturnCode;
private int mResultCode;
private Intent mResultIntent;
private boolean mUploadFileOnLoad = false;
当我们从摄像头返回活动时,将调用onActivityResult
。如果活动被重建,则mUploadMessage为空。因此,我们将参数保存到字段中,并将mUploadFileOnLoad
设置为true并返回。其他部分非常重要。
@Override
protected void onActivityResult(int requestCode,
int resultCode,
Intent intent)
{
//if the callback object has been recycled
if(null==mUploadMessage)
{
//Save the result
mReturnCode = requestCode;
mResultCode = resultCode;
mResultIntent = intent;
//remember to invoke file upload using Javascript
mUploadFileOnLoad = true;
return;
}else
mUploadFileOnLoad = false;
//rest of the code
}
此解决方案的重要部分位于WebViewClient
和WebChromeClient
new WebChromeClient() {
//Other overloaded functions
//See http://stackoverflow.com/a/15423907/375093 for full explanation
//The undocumented magic method override
//Eclipse will swear at you if you try to put @Override here
// For Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
//If we lost the callback object
if(mUploadFileOnLoad)
{
mUploadMessage = uploadMsg;
//use the saved result objects to invoke onActivityResult
onActivityResult(mReturnCode, mResultCode, mResultIntent);
return;
}
//Rest of the code....
}
和
new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
if(mUploadFileOnLoad)
{
webview.loadUrl("javascript:document.getElementById('my_file').click()");
}
}
在上面,my_file
是
<input type="file" id="my_file">
总之,我们所做的是——当我们没有回调对象时,我们保存从其他活动接收的数据,并将
mUploadFileOnLoad
设置为true,然后等待页面加载。当页面加载时,我们使用Javascript来调用文件选择器,从而得到一个回调对象。因为我们已经有了结果,所以我们调用activityresult并返回。onActivityResult现在有一个来自webview的回调。
我假设实际调用了onActivityResult
方法,但第三个参数Intent-Intent
为空。这似乎是Nexus手机的一个缺陷。
但是您可以将输出图像uri保存到私有变量中,并使用它而不是意图:
private Uri imageUri;
private void showAttachmentDialog(ValueCallback<Uri> uploadMsg) {
this.mUploadMessage = uploadMsg;
File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "TestApp");
if (!imageStorageDir.exists()) {
imageStorageDir.mkdirs();
}
File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
this.imageUri = Uri.fromFile(file); // save to the private variable
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[] { captureIntent });
this.startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result;
if (resultCode != RESULT_OK) {
result = null;
} else {
result = intent == null ? this.imageUri : intent.getData(); // retrieve from the private variable if the intent is null
}
this.mUploadMessage.onReceiveValue(result);
this.mUploadMessage = null;
}
}
在这段代码中,我将imageUri
变量添加到活动中,并在两种方法中使用它。
在苦苦挣扎之后,我找到了一个代码,可以从galley和5.0设备上获取文件
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageURI = null;
private ValueCallback<Uri[]> mFilePathCallback;
private String mCameraPhotoPath;
private static final int INPUT_FILE_REQUEST_CODE = 1;
private static final int FILECHOOSER_RESULTCODE = 1;
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return imageFile;
}
这是初始化和设置webview
mWebView= (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginState(WebSettings.PluginState.OFF);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setUserAgentString("Android Mozilla/5.0 AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30");
mWebView.getSettings().setAllowFileAccess(true);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.getSettings().setAllowContentAccess(true);
mWebView.getSettings().supportZoom();
mWebView.loadUrl(Common.adPostUrl);
mWebView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// do your handling codes here, which url is the requested url
// probably you need to open that url rather than redirect:
if ( url.contains(".pdf")){
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "application/pdf");
try{
view.getContext().startActivity(intent);
} catch (ActivityNotFoundException e) {
//user does not have a pdf viewer installed
}
} else {
mWebView.loadUrl(url);
}
return false; // then it is not handled by default action
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.e("error",description);
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) { //show progressbar here
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
//hide progressbar here
}
});
mWebView.setWebChromeClient(new ChromeClient());
这是我的ChomeClient()方法
public class ChromeClient extends WebChromeClient {
// For Android 5.0
public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
// Double check that we don't have any existing callbacks
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePath;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(Common.TAG, "Unable to create Image File", ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
return true;
}
// openFileChooser for Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
// Create AndroidExampleFolder at sdcard
// Create AndroidExampleFolder at sdcard
File imageStorageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)
, "AndroidExampleFolder");
if (!imageStorageDir.exists()) {
// Create AndroidExampleFolder at sdcard
imageStorageDir.mkdirs();
}
// Create camera captured image file path and name
File file = new File(
imageStorageDir + File.separator + "IMG_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg");
mCapturedImageURI = Uri.fromFile(file);
// Camera capture image intent
final Intent captureIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
// Create file chooser intent
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
// Set camera intent to file chooser
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS
, new Parcelable[] { captureIntent });
// On select image call onActivityResult method of activity
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
// openFileChooser for Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
openFileChooser(uploadMsg, "");
}
//openFileChooser for other Android versions
public void openFileChooser(ValueCallback<Uri> uploadMsg,
String acceptType,
String capture) {
openFileChooser(uploadMsg, acceptType);
}
}
//下面是我的onActivityResult方法,用于处理来自图库或相机的数据
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
String dataString = data.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
} else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e,
Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
return;
}
这是打开摄像头所需的权限
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.CAMERA2" /> // for new versions api 21+
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
注意:我的代码也包含运行3.0的设备的代码,但我从未测试过它们,上面的代码适用于Lollipop、Marshmallow和牛轧糖模拟器。还有一件事,如果你看到Android系统的图标代替相机,这意味着你的设备中有许多应用程序可以用来处理相机。
嘿,谢谢你抽出时间。在我的页面中,我的应用程序的webview中加载的是照片上传: 它上传一张照片,如果你通常图片你的画廊等... 如果我点击这个输入,我可以选择一张图片,然后网站检测到更改(js:onchange)。我已经尝试了一些东西,但在我选择它之后它不会上传图片。下面是我对imgupload的编码: 我希望你能帮忙,祝你今天过得愉快
我有4个Different imageview,并尝试单击所有以上传不同的图像,如许可证、Rc、配置文件等。我希望从画廊或相机对话框上传图像。类似于此布局。类似于超级布局示例
背景:我正在尝试构建一个非常基本的WebView应用程序,用于访问我最近构建的响应性web应用程序/网站。该网站的一个功能包括一个“选择照片”按钮,用户可以将图像上传到HTML5画布上进行临时图像查看和数据提取。此按钮基于简单的HTML文件输入: 该功能在“常规”移动浏览器(各种Android和iOS设备上的Chrome、Safari、Firefox等)中都能完美运行。当用户在这些浏览器中点击“选
我按照这个从网络视图中捕获或选择文件并上传。。。这是完美的,适用于所有android版本。。 所以在那里,我想添加作物意图。。。在相机拍摄/画廊后进行裁剪,然后从Webview上传所有这些内容 我想为Crop Image添加以下内容:。。我想在MainActivity中添加这个。。以相机和画廊的形式拍摄。。 所以我想裁剪并上传的可能是相机或画廊。。 有谁能建议我如何在主要活动中添加作物意图吗。。
我的应用程序(Android 4.4.4)中嵌入的webview有问题。在一个页面上有一个“上传图像”按钮,我用openFileChooser管理它。 在某些设备上,当我点击webview中的“上传图像”按钮时,摄像头应用程序启动,我的应用程序被销毁。拍照后,我的应用程序被重新创建,我恢复webview状态(保存在)并调用
此外,文件浏览器在选择存储在设备本身的图像/PDF时工作,但通过这种方法从Google Drive上传的文件不能正确上传。有什么想法吗?