首页 > 代码库 > 通过camera + gallery android上传文件到html

通过camera + gallery android上传文件到html

  今天做项目的时候遇到一个问题:当html通过js调用input of type file时候,希望android手机的选择器可以同时出现“相机”和“图片”等,但通过下面代码

Intent i = new Intent(Intent.ACTION_GET_CONTENT);i.addCategory(Intent.CATEGORY_OPENABLE);i.setType("image/*");((Activity) mContext).startActivityForResult(Intent.createChooser(i, "Image Choser"), 1);

只显示了“图片”,“文件管理器”等,就是没有“相机”!!!于是google了下找到类下面的方法

final List<Intent> cameraIntents = new ArrayList<Intent>();final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);File externalDataDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);File cameraDataDir = new File(externalDataDir.getAbsolutePath()+File.separator+"browser-photos");cameraDataDir.mkdirs();String mCameraFilePath = cameraDataDir.getAbsolutePath()+File.separator+System.currentTimeMillis()+".jpg";imageUri = Uri.fromFile(new File(mCameraFilePath));final PackageManager packageManager = getPackageManager();final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);for(ResolveInfo res : listCam) {   final String packageName = res.activityInfo.packageName;   final Intent intent = new Intent(captureIntent);   intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));   intent.setPackage(packageName);   intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);   cameraIntents.add(intent);}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);

简单运行下,perfect完美!!!

  简单小结:通过上面的代码其实可以添加多种你想要的类型应用不止仅限于“相机”的。

另附上相关链接:猛搓Me 、 input file解决方法

通过camera + gallery android上传文件到html