Norbert
Norbert

Reputation: 7750

how do I check the file size of a video in flutter before uploading

I want to upload a video file to my cloud storage but I want to check the size of the video file before I upload. how to achieve this

Upvotes: 58

Views: 64432

Answers (5)

Mubashar Hussain
Mubashar Hussain

Reputation: 305

import 'dart:io';

//Here's the method to get file size:

double getFileSize(File file){      
    int sizeInBytes = file.lengthSync();
    double sizeInMb = sizeInBytes / (1024 * 1024);
    return sizeInMb;
}

//Alternatively for extension:

extension FileUtils on File {
    get size {
        int sizeInBytes = this.lengthSync();
        double sizeInMb = sizeInBytes / (1024 * 1024);
        return sizeInMb;
    }
}

Upvotes: 2

Zeeshan Ansari
Zeeshan Ansari

Reputation: 1483

If you are using the latest ImagePicker with xFile type then,

 final XFile? photo = await _picker.pickImage(source: ImageSource.camera);
  print(File(photo.path).lengthSync());

will return the file size in bytes.

Upvotes: 5

Kamlesh
Kamlesh

Reputation: 6145

// defined the function

getFileSize(String filepath, int decimals) async {
    var file = File(filepath);
    int bytes = await file.length();
    if (bytes <= 0) return "0 B";
    const suffixes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
    var i = (log(bytes) / log(1024)).floor();
    return ((bytes / pow(1024, i)).toStringAsFixed(decimals)) + ' ' + suffixes[i];  
}

// how to call the function

print(getFileSize('file-path-will-be-here', 1));

// output will be as string like:

97.5 KB

This worked for me. I hope, this will also help you. Thanks a lot for asking question.

Upvotes: 58

sushant singh
sushant singh

Reputation: 788

This is work for me.

final file = File('pickedVid.mp4');            
int sizeInBytes = file.lengthSync();
double sizeInMb = sizeInBytes / (1024 * 1024);
if (sizeInMb > 10){
    // This file is Longer the
}

Upvotes: 18

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657781

If you have the path of the file, you can use dart:io

var file = File('the_path_to_the_video.mp4');

You an either use:

print(file.lengthSync()); 

or

print (await file.length());

Note: The size returned is in bytes.

Upvotes: 120

Related Questions