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

前端 未结 3 729
慢半拍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条回答
  •  猫巷女王i
    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.

提交回复
热议问题