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

Time:04-23

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?

CodePudding user response:

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';
    }
  }

CodePudding user response:

If you don't have the original filename, there's no way to recover it. That's metadata that's not part of the file's content, and base64 encoding operates only on the file's content. It'd be best if you could save the original filename.

If you can't, you can use package:mime to guess the MIME type of the file from a small amount of binary data. You could decode the first n×4 characters from the base64 string (a valid base64 string must have a length that's a multiple of 4), decode it, and call lookupMimeType.

package:mime has a defaultMagicNumbersMaxLength value that you can use to compute n dynamically:

import 'dart:convert';
import 'package:mime/mime.dart' as mime;

String? guessMimeTypeFromBase64(String base64String) {
  // Compute the minimum length of the base64 string we need to decode
  // [mime.defaultMagicNumbersMaxLength] bytes.  base64 encodes 3 bytes of
  // binary data to 4 characters.  
  var minimumBase64Length = (mime.defaultMagicNumbersMaxLength / 3).ceil() * 4;
  return mime.lookupMimeType(
    '',
    headerBytes: base64.decode(base64String.substring(0, minimumBase64Length)),
  );
}

For the types that package:mime supports as of writing, mime.defaultMagicNumbersMaxLength is 12 (which translates to needing to decode the first 16 bytes from the base64 string).

  • Related