dartangular-dart

Get MIME type of File object


I have a dart:html File object and I want to determine the MIME type from the file contents rather than the extension.


Solution

  • You can use the mime package's function lookupMimeType and pass in the headerBytes by calling slice on the File with defaultMagicNumbersMaxLength

    import 'dart:async';
    import 'dart:html';
    import 'package:mime/mime.dart' as mime;
    
    Future<String?> getMimeType(File file) async {
      // Create a slice for the header.
      final slice = file.slice(0, mime.defaultMagicNumbersMaxLength);
    
      // Read the file header's contents.
      final fileReader = FileReader();
      fileReader.readAsArrayBuffer(slice);
      await fileReader.onLoad.first;
      final header = fileReader.result as List<int>;
    
      // Empty string for the file name because it's not relevant.
      return mime.lookupMimeType('', headerBytes: header);
    }