从相机拍摄并上传照片时出现错误。

huangapple go评论76阅读模式
英文:

Error when upload a photo tacken from the camera

问题

我是 Android Studio 和移动应用开发的初学者,但我仍在努力学习。因此,我已经成功构建了我的第一个 WebView 应用程序来显示一个网页和一张图片。我找到了许多有用的资源,帮助我完成了这个任务,但我仍然在尝试解决一个问题,即如何从手机相机(而不是图库)直接拍摄照片并上传到服务器。

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

> -1_net::ERR_ACESS_DENIED

以下是我的 onActivityResult 代码:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        // ...
        mUploadMessage.onReceiveValue(result);
        mUploadMessage = null;
    } 
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // ...
        mFilePathCallback.onReceiveValue(results);
        mFilePathCallback = null;
    } // end of code for Lollipop only
}

------ 这是 openFileChooser 的部分 ------

public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
    mUploadMessage = uploadMsg;
    // 设置 WebView 的一些设置
    try {
        File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "DirectoryNameHere");
        // ...

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

非常感谢您的帮助。

英文:

I am a beginner to android studio and to mobile apps developing in general , however i am still trying to learn .
so I have managed to build my first webview app to show a page and a picture.I found a lot of useful resources that helped me to do so , but i am still facing a problem with uploading a photo taken from the phone camera ( not from the gallery ) directly and upload to the server .

1- after I press on the brows button the app prompts me whether to take the picture from the camera or from the gallery. ( Android version 9 )
2- when i upload a photo from the gallery the app works fine , but when I use the camera to take a photo and upload startight away it does not work. it gives me the following error message although the photo name returned to the field path

> -1_net::ERR_ACESS_DENIED

here is my onActivityResult code

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (Build.VERSION.SDK_INT &lt; 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(), &quot;activity :&quot; + e, Toast.LENGTH_LONG).show();
            }

            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        }

    } 
    if (Build.VERSION.SDK_INT &gt;= 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
}

-------and here is the openFileChooser ----------------

 public void openFileChooser(ValueCallback&lt;Uri&gt; 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), &quot;DirectoryNameHere&quot;);

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

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

                    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(&quot;image/*&quot;);

                    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(), &quot;Camera Exception:&quot; + e, Toast.LENGTH_LONG).show();
                }

            }
      
I really appreciate your help 



</details>


# 答案1
**得分**: 0

```java
仅在清单中放置是不够的,您必须发出请求以获取权限,

if (ContextCompat.checkSelfPermission(this, 
    Manifest.permission.REQUESTED_PERMISSION) == PackageManager.PERMISSION_GRANTED) 
{
    // 您可以使用需要权限的 API
    openFileChooser();
} else {
    requestPermissions(this, new String[] { 
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.CAMERA
    }, 100);
}

@Override
public void onRequestPermissionsResult(
    int requestCode, String[] permissions, int[] grantResults) 
{
    if (requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        openFileChooser();
    } else {
        // 未授予权限,显示提示信息或对话框
    }
}
英文:

not enough just put in manifest,you must launch requet permission,

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 &amp;&amp; grantResults[0] == PackageManager.PERMISSION_GRANTED){
        openFileChooser();
    }else{
        //not grant show toas or dialog
    }
}

答案2

得分: 0

我已经为我的问题找到了解决方案。
经过调试,我意识到我放在createImageFile()中的图像文件夹路径不存在且未被创建,所以我用以下代码替换了我的createImageFile(),并且它对我起作用了:

String currentPhotoPath;

private File createImageFile() throws IOException {
    // 创建图像文件名
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
        imageFileName,  /* 前缀 */
        ".jpg",         /* 后缀 */
        storageDir      /* 目录 */
    );

    // 保存文件路径以供ACTION_VIEW意图使用
    currentPhotoPath = image.getAbsolutePath();
    return image;
}

感谢大家的帮助。

英文:

I have found a solution for my problem .
after debuging I have realised that the path of the images folder that I put in the createImageFile() is not exists and not created , so i replaced my createImageFile() with the following code and it worked with me

String currentPhotoPath;

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat(&quot;yyyyMMdd_HHmmss&quot;).format(new Date());
    String imageFileName = &quot;JPEG_&quot; + timeStamp + &quot;_&quot;;
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
        imageFileName,  /* prefix */
        &quot;.jpg&quot;,         /* suffix */
        storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    currentPhotoPath = image.getAbsolutePath();
    return image;
}

Thank you all for your help .

huangapple
  • 本文由 发表于 2020年9月22日 02:14:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/63997851.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定