Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get type of file?

Tags:

flutter

dart

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

like image 675
delmin Avatar asked Jun 13 '20 15:06

delmin


People also ask

How do I identify a file type?

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.

What command can you use to find the file type of a file?

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).

How do I view a file type in Linux?

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.

How do I change a file type?

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.


1 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
like image 117
creativecreatorormaybenot Avatar answered Oct 10 '22 22:10

creativecreatorormaybenot