File length is 0 when recreating file from URI, or original filepath [getExternalFilesDir(String type) vs getFilesDir()]

前端 未结 3 621
慢半拍i
慢半拍i 2021-01-14 02:09

A little bit of background first: this app takes a picture and uploads to an Azure blob storage.

The picture is stored in a file (internal storage) using getA

相关标签:
3条回答
  • 2021-01-14 02:21

    Found a workaround. This is the function I was using to get the file that was being passed to the Camera intent.

        // Create a File object for storing the photo
        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 = getApplicationContext().getFilesDir();
    
        mPhotoFileExists = true;
    
        // check if access to external storage exists
        // if returned true, return the new file
        // if returned false, user could have been requested for access
        // so, need to check if permission is available now
        // if still not available, return null
    
        if(haveWritePermissions())
            return File.createTempFile(
                    imageFileName,  /* prefix */
                    ".jpg",         /* suffix */
                    storageDir      /* directory */
            );
        return null;
        }
    

    I changed the storageDir from getApplicationContext().getFilesDir(); to getApplicationContext.getExternalFilesDir(null);

    Docs: getExternalFilesDir(String type), getFilesDir()

    I passed null since I didn't want to put Environment.DIRECTORY_PICTURES, which would allow the Media Scanner to find the image file.

    I understand that this, in no way, is a 'fix'. Still looking for an answer as to why getFilesDir() is causing this issue.

    EDIT: Very pressing reason as to why this is not a good solution - external storage may not always be available, and there would not be any workaround in that case. Also, any other app with permission WRITE_EXTERNAL_STORAGE can write here. So, no security is enforced either.

    0 讨论(0)
  • 2021-01-14 02:41

    Even though I don't have all the information, I'm gonna make the call that the file is missing from the path you've given. The javadoc for length() specifically mentions this case will return 0.

    So try checking exists() before you do anything with the file.

    0 讨论(0)
  • 2021-01-14 02:44

    While using internal storage the file path is different. I think it is stored in /storage/emulated in latest devices. Check for your file path. and see if you are creating a file with the absolute path.

    0 讨论(0)
提交回复
热议问题