【问题标题】:Error when upload a photo tacken from the camera上传从相机拍摄的照片时出错
【发布时间】:2020-09-21 18:14:53
【问题描述】:

我是 android studio 和一般开发的移动应用程序的初学者,但我仍在努力学习。 所以我设法构建了我的第一个 webview 应用程序来显示页面和图片。我找到了很多有用的资源来帮助我这样做,但我仍然面临上传从手机相机拍摄的照片的问题(不是从图库)直接上传到服务器。

1- 在我按下浏览按钮后,应用程序会提示我是从相机还是从图库中拍照。 (安卓版本 9) 2- 当我从图库上传照片时,该应用程序工作正常,但是当我使用相机拍照并立即上传时,它不起作用。尽管照片名称返回到字段路径,但它给了我以下错误消息

-1_net::ERR_ACES_DENIED

这是我的 onActivityResult 代码

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        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;
        }

    } 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

        if (requestCode != FILECHOOSER_RESULTCODE || mFilePathCallback == null) {
            super.onActivityResult(requestCode, resultCode, data);
            return;
        }

        Uri[] results = null;      
        if (resultCode == Activity.RESULT_OK) {
            if (data == null || data.getData() == 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;

    } // end of code for Lollipop only
}

-------这里是openFileChooser ----

 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                mWebView.getSettings().setJavaScriptEnabled(true);
                mWebView.getSettings().setAllowFileAccess(true);
                mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
                mWebView.getSettings().setDomStorageEnabled(true);
                mWebView.getSettings().setLoadsImagesAutomatically(true);

                try {
                    File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "DirectoryNameHere");

                    if (!imageStorageDir.exists()) {
                        imageStorageDir.mkdirs();
                    }

                    File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");

                    mCapturedImageURI = Uri.fromFile(file); // save to the private variable

                    final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
                    // captureIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

                    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                    i.addCategory(Intent.CATEGORY_OPENABLE);
                    i.setType("image/*");

                    Intent chooserIntent = Intent.createChooser(i, getString(R.string.image_chooser));
                    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});

                    startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
                } catch (Exception e) {
                    Toast.makeText(getBaseContext(), "Camera Exception:" + e, Toast.LENGTH_LONG).show();
                }

            }
      
I really appreciate your help 

【问题讨论】:

  • @blackapps 我已经删除了不必要的代码,只发布了 onActivityResult 和 openFileChooser。
  • 您也可以删除清单文件。并且全部使用Intent i,因为它没有被使用。
  • imageStorageDir.mkdirs(); 检查返回值。如果 false 为用户显示 Toast,则告诉用户。并返回。那就不要继续了。
  • onActivityResult 中有很多代码。一团糟。仅将使用相机时需要的代码放入其中。并且仅适用于产生问题的构建。
  • 你检查读写外部存储和相机权限吗?在调用 openFileChooser 之前?

标签: java android android-studio file-upload webview


【解决方案1】:

仅仅放入manifest还不够,你必须启动requet权限,

if (ContextCompat.checkSelfPermission(this, 
    Manifest.permission.REQUESTED_PERMISSION) ==PackageManager.PERMISSION_GRANTED) 
{
    // You can use the API that requires the permission
    openFileChooser();
}else{
    requestPermissions(this,new String[] { 
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.CAMERA},100
        );
}
@Override
public void onRequestPermissionsResults(
    int requestCode, String[] permissions,int[] grantResults) 
    {
    if (requestCode==100 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
        openFileChooser();
    }else{
        //not grant show toas or dialog
    }
}

【讨论】:

    【解决方案2】:

    我找到了解决问题的方法。 调试后我意识到我放在 createImageFile() 中的图像文件夹的路径不存在并且没有创建,所以我用下面的代码替换了我的 createImageFile() 并且它对我有用

    String currentPhotoPath;
    
    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 = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
        );
    
        // Save a file: path for use with ACTION_VIEW intents
        currentPhotoPath = image.getAbsolutePath();
        return image;
    }
    

    谢谢大家的帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多