{

Dart| Flutter How to get extension name and MIME type of a file with example


get the File name and MIME type of a file dart or flutter

This tutorial explains about below program

  • How to get the MIME type of a file
  • How to find the extension of a given file

How to get the MIME type of file?

This program explains about to get mime types of a file.

The mime package provides a lookupMimeType function, that returns the MIME type.

It parses the path of a file, returns extension, extension is checked against MIME types, and returns the MIME-type

Here is an example program

import 'package:mime/mime.dart';

void main() {
  print(getExtension("test.doc")); //application/msword
  print(getExtension("abc.pdf")); //application/pdf
  print(getExtension("photo.png")); //image/png
  print(getExtension("test.jpg")); //image/jpeg
  print(getExtension("config.xml")); //application/xml
  print(getExtension("abc.json")); //application/json
}

String getExtension(String path) {
  final mimeType = lookupMimeType(path);
  return mimeType;
}

Dart gets file extension

There are multiple ways to get the extension name of a file.

For example, if the given file is input.png, then the extension is png.

One way, using a split function

Create a function, that accepts a file path Inside a function, split the path using. separator and returns the parts of a string.

  List<String> split(Pattern pattern);

It returns the list of strings with parts. The last element is an extension that can be get using List.last property.

Here is an example program

void main() {
  print(getExtension("test.png"));
  print(getExtension("abc/test.png"));
}

String getExtension(String fileName) {
  return  fileName.split('.').last;
}

Output:

test
png

The above program fails if an extension is not found.

Let’s see another way is using path package.

The Path package provides functions to process split and join operations on file system files.

Path provides an extension function

String extension(String path, [int level = 1])

level returns multiple extensions including include number of dots(.)

Here is an example program

import 'package:path/path.dart' as p;

void main() {
  print(getExtension("test"));
  print(getExtension("abc/test.png"));

  print(getExtension1("test", 1)); //returns empty
  print(getExtension1("abc.test.png", 2)); //.test.png
  print(getExtension1("abc.test.png", 1)); //.png
  print(getExtension1("abc.png", 1)); //.png
}

String getExtension1(String path, [int level]) {
  final extension = p.extension(path, level);
  return extension;
}
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.