1

I've tried the answers on every other post out there and they all seem to return 0.0 as the file size of my image which cannot be true. I think the file path is what's causing it to return the incorrect file size. Here is my code:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            imageUri = data.getData();
            textViewImageAttachmentStatus.setText("File has been attached");
            textViewImageAttachmentStatus.setTextColor(Color.parseColor("#008577"));
            Picasso.get().load(imageUri).into(imageViewPreviewImage);

            String imagePath = imageUri.getPath();
            File imageFile = new File(imagePath);
            long imageSize = imageFile.length() / 1024;
            System.out.println(imageSize);
        }
    }
Raf A
  • 179
  • 1
  • 12

5 Answers5

3

Better use Cursor its much robust , Try this

Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            assert cursor != null;
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            mediaPath1 = cursor.getString(columnIndex);
            cursor.close();
            File file = new File(mediaPath);
            int file_size = Integer.parseInt(String.valueOf(file.length() / 1048576));
            System.out.println(file_size);
Vish
  • 404
  • 3
  • 17
0

You can try this code

Import below packages

import java.io.File;
import java.text.DecimalFormat;

put below code when it requires

private static final DecimalFormat format = new DecimalFormat("#.##");
private static final long MiB = 1024 * 1024;
private static final long KiB = 1024;

public static String getFileSize(File file) {

    if (!file.isFile()) {
        throw new IllegalArgumentException("Expected a file");
    }
    final double length = file.length();

    if (length > MiB) {
        return format.format(length / MiB) + " MB";
    }
    if (length > KiB) {
        return format.format(length / KiB) + " KB";
    }
    return format.format(length) + " Bytes";
}

Call the above function

String fileSize = getFileSize(imageFile);
Parth Patel
  • 859
  • 2
  • 11
  • 28
0

Here is code for get file size from choose from Gallery

 case AppConstant.REQUEST_GALLERY_IMAGE:
            if (resultCode == Activity.RESULT_OK) {
                long dataSize = 0;
                File f = null;
                Uri uri = data.getData();
                String scheme = uri.getScheme();
                System.out.println("Scheme type " + scheme);
                if (scheme.equals(ContentResolver.SCHEME_CONTENT)) {
                    try {
                        InputStream fileInputStream = getApplicationContext().getContentResolver().openInputStream(uri);
                        dataSize = fileInputStream.available();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Log.e("File Size Length", dataSize + ""); // Here get file sizw
                } else if (scheme.equals(ContentResolver.SCHEME_FILE)) {
                    String path = uri.getPath();
                    try {
                        f = new File(path);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Log.e("File Size Length", f.length() + ""); // here get file size
                }
            }
        break;
Arti
  • 672
  • 7
  • 19
  • The IDE shows "Cannot resolve symbol AppConstant" - any ideas? I can't find anything online regarding this. – Raf A Jan 02 '20 at 13:38
  • I have use switch case in onActivityResult So that Static Request code in AppConstant. You use this code "if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK )" inside if – Arti Jan 03 '20 at 05:09
0
Here the value is returned, for example, if you want not to upload a file larger than 5 megabytes 
public boolean MaxSizeImage(String imagePath){

    long file_size = new File(imagePath).length() / 1024;//"kB"
    if (file_size <=  5000){ //5M
        return true;
    }

    return false;
}
//Here the path is fetched
public static String getFilePath(Context context, Uri uri) {
    String imagePath;
    String[] filePath = {MediaStore.Images.Media.DATA};
    Cursor c = context.getContentResolver().query(uri, filePath, null, null, null);
    assert c != null;
    c.moveToFirst();
    int columnIndex = c.getColumnIndex(filePath[0]);
    imagePath = c.getString(columnIndex);
    c.close();
    return imagePath;
}
0

Here's a simpler and more sofisticated way of getting the size of a file that the user has just selected. Please see if this snippet might helps.

Uri returnUri = intent.getData();
Cursor returnCursor = getContentResolver().query(returnUri, null, null, null, null);

int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
String selectedFileName = returnCursor.getString(nameIndex);
Long selectedFileSize = Long.toString(returnCursor.getLong(sizeIndex));

Full documentation here where you can also find this snippet written in Kotlin.

leoneboaventura
  • 415
  • 1
  • 3
  • 13