flutterfilepicker

How to set maximum size of file from File Picker in Flutter


this is my code

Uint8List? filePath1;
  File? file1;


  Future transferCertificatePick() async {

    final result = await FilePicker.platform.pickFiles();

    if (result == null) return;
    Uint8List? fileBytes1 = result.files.first.bytes;
    final path = result.files.first.name;
    setState(() {
      file1 = File(path);
      filePath1 = fileBytes1;
    });
  }

Solution

  • Deprecated Answer:

    To set a maximum file size for the selected file, you can use the maxFileSize parameter when calling the FilePicker method.

    final result = await FilePicker.platform.pickFiles(
      maxFileSize: 5 * 1024 * 1024, // 5MB in bytes
    );
    

    Updated Answer:

    You can get the size of the picked file with result.files.first.size and check if it's less than the max size or not. Here is an example.

    
    double _sizeKbs = 0;
    final int maxSizeKbs = 1024;
    
    void onFilePicked() async {
        FilePickerResult? result = await FilePicker.platform.pickFiles();
        if(result != null) {
          final size = result.files.first.size;
          _sizeKbs = size/1024;
          if(_sizeKbs > maxSizeKbs) {
            print('size should be less than $maxSizeKbs Kb');
          } else {
            print('file size accepted');
            //Upload your file
          }
        }
    }