从相机上传的照片在 Nexus、Android WebView 中不起作用

Posted

技术标签:

【中文标题】从相机上传的照片在 Nexus、Android WebView 中不起作用【英文标题】:Photo upload from Camera not working in Nexus, Android WebView 【发布时间】:2017-04-09 10:34:51 【问题描述】:

我正在开发 android webview。从Nexus 5 中的Camera 操作上传图像时遇到问题。在这里,相机打开,我单击图像但没有任何反应,图像无法上传。但它适用于 Document 或 Gallery。有很多解决方案和this。但我无法解决我的问题。有什么办法可以解决这个问题?

在我的清单文件中,我包括:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

在我的活动中,我包括:

private static final int INPUT_FILE_REQUEST_CODE = 1;
private static final int FILECHOOSER_RESULTCODE = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private WebView webView;
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageURI = null;
private ValueCallback<Uri[]> mFilePathCallback;
private String mCameraPhotoPath;

@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;

对于我的 WebChromeClient,我包括:

public class MyWebChromeClient 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(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)
                , "Photo Folder");

        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");
        Log.d("File", "File: " + file);
        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);
    

在这里可以做什么,以便通过相机操作上传图像?

【问题讨论】:

【参考方案1】:

我通过更改onActivityResult 方法中的以下代码行来解决我的相机问题:

 if (resultCode == Activity.RESULT_OK) 
            if (data == null || data.getDataString() == 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);
                
            
        

我添加这个:if (data == null || data.getDataString() == null) ...

【讨论】:

你的 createImageFile() 方法是什么? 我错过了那部分。已经有一段时间了。如果您想查看,可以在这里找到 repo:github.com/SatanPandeya/file_chooser_webview 谢谢!其实我已经找了一段时间了。我查看了很多 repo,它们的代码几乎完全相同,但由于某种原因,它们在第一次检查中都缺少 || data.getDataString() == null 部分。 添加 || data.getDataString() == null 部分是解决方案!太好了!【参考方案2】:

android:requestLegacyExternalStorage="true" 添加到清单中的应用程序标签

【讨论】:

以上是关于从相机上传的照片在 Nexus、Android WebView 中不起作用的主要内容,如果未能解决你的问题,请参考以下文章

在 android 6.0.1 中,检索相机照片不起作用

使用相机拍摄照片时数据为空(Nexus 7)

firebase 存储 - 使用 android 相机上传照片,但在将照片提交到 firebase 存储时崩溃

Android Studio 调用系统相机(超清)和相册的照片并显示在ImageView

Android实现批量照片上传至server,拍照或者从相冊选择

无法上传照片库视频,但可以上传从相机 iOS 拍摄的视频