How to get type of file?

Viewed 17971

I'm trying to find a package which would recognise file type. For example

final path = "/some/path/to/file/file.jpg";

should be recognised as image or

final path = "/some/path/to/file/file.doc";

should be recognised as document

3 Answers

You can make use of the mime package from the Dart team to extract the MIME types from file names:

import 'package:mime/mime.dart';

final mimeType = lookupMimeType('/some/path/to/file/file.jpg'); // 'image/jpeg'

Helper functions

If you want to know whether a file path represents an image, you can create a function like this:

import 'package:mime/mime.dart';

bool isImage(String path) {
  final mimeType = lookupMimeType(path);

  return mimeType.startsWith('image/');
}

Likewise, if you want to know if a path represents a document, you can write a function like this:

import 'package:mime/mime.dart';

bool isDocument(String path) {
  final mimeType = lookupMimeType(path);

  return mimeType == 'application/msword';
}

You can find lists of MIME types at IANA or look at the extension map in the mime package.

From file headers

With the mime package, you can even check against header bytes of a file:

final mimeType = lookupMimeType('image_without_extension', headerBytes: [0xFF, 0xD8]); // jpeg

There is no need of any extension. You can try below code snippet.

String getFileExtension(String fileName) {
 return "." + fileName.split('.').last;
}

If think you should take a look to path package, specially to extension method.
You can get file format without adding one more package to pubspec.yaml ;)

context.extension('foo.bar.dart.js', 2);   // -> '.dart.js
context.extension('foo.bar.dart.js', 3);   // -> '.bar.dart.js'
context.extension('foo.bar.dart.js', 10);  // -> '.bar.dart.js'
context.extension('path/to/foo.bar.dart.js', 2);  // -> '.dart.js'
Related