flutterdartbase64flutter-dependenciesflutter-web

How to get file extension from base64 String in Flutter | Dart


I have a base64 string of a document from api. I want to know which extension/file format is that. Because if it is in jpg/jpeg/png i want to show it in image widget. Or if it is in pdf format i want to show it in PdfView widget. So is there any way to get file extension from base64. Is there any package for it?


Solution

  • If you have a base64 string you can detect file type by checking the first character of your base64 string:

    '/' means jpeg.

    'i' means png.

    'R' means gif.

    'U' means webp.

    'J' means PDF.

    I wrote a function for that:

    String getBase64FileExtension(String base64String) {
        switch (base64String.characters.first) {
          case '/':
            return 'jpeg';
          case 'i':
            return 'png';
          case 'R':
            return 'gif';
          case 'U':
            return 'webp';
          case 'J':
            return 'pdf';
          default:
            return 'unknown';
        }
      }