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
Click Start. Open Control Panel, click Control Panel Home, and click Programs. Click Default Programs, and click Associate a file type or protocol with a program. On this screen, the registered file types are displayed.
The file command uses the /etc/magic file to identify files that have a magic number; that is, any file containing a numeric or string constant that indicates the type. This displays the file type of myfile (such as directory, data, ASCII text, C program source, or archive).
To find out file types we can use the file command. Using the -s option we can read the block or character special file. Using -F option will use string as separator instead of “:”. We can use the –extension option to print a slash-separated list of valid extensions for the file type found.
You can also do it by right-clicking on the unopened file and clicking on the “Rename” option. Simply change the extension to whatever file format you want and your computer will do the conversion work for you.
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'
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.
With the mime
package, you can even check against header bytes of a file:
final mimeType = lookupMimeType('image_without_extension', headerBytes: [0xFF, 0xD8]); // jpeg
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With