Dart/Flutter - Get Mime Type of a File or URL Examples

This tutorial is about how to get the mime type of a file or URL using Dart.

Determining the type of a file is not as simple as parsing the extension from a file or URL. A proper way is by getting the mime type of the object. If your application is developed using Dart including any of its Framework such as Flutter, you can obtain the mime type in a fairly easy way. This tutorial is divided into two parts. The first one is how to get the mime type of a local file. The other part is how to get the mimetype from a URL.

Get Mime Type of a Local File

A file name usually contains the extension of the file. However, it doesn't guarantee that the extension of the file name matches the actual content of the file because the extension can be renamed to any value without changing the content of the file. For cases where you need to properly know the type of a file, it can be done by getting the mime type of the file. For that purpose, Dart has a package called mime which can be used to get the mime type of a local file.

Modify your pubspec.yaml file to add the below dependency and run flutter pub get.

  dependencies:
    mime: ^1.0.4

To use the package, add import 'package:mime/mime.dart'; on the top of the file where you need to get the mime type from a local file path. Then, call the lookupMimeType method by passing the file path as the first argument.

  String? _getFileMimeType(String path) {
    return lookupMimeType(path);
  }

The method above may return a null value. For example, if the path doesn't exist or is not a file.

Get Mime Type of a URL

Even if the URL contains the extension of the file that it represents, it's not recommended to get the content type of a URL from the file extension. The correct way to determine the type of the response data is from the mime type. If you need to get the mime type from a URL resource, it can be obtained from the content-type of the response headers, assuming the value is accurate. Therefore, you need to make a request to the URL.

If the URL uses HTTP/HTTPS protocol, you can use Dart's http package. Add the following dependency in your pubspec.yaml file and run flutter pub get afterwards.

  dependencies:
    http: ^0.13.5

After that, add import 'package:http/http.dart' as http; at the top of the file where you want to get the mime type of a URL. Then, add the code for performing an HTTP request. If you only need to get the mime type without getting the content of the file, it's recommended to use the HEAD method, which only returns the response headers. After the request completes, you can get the content-type header from the response which contains the mime type.

  Future<String?> _getUrlMimeType(String url) async {
    final response = await http.head(Uri.parse(url));

    return response.headers['content-type'];
  }

Flutter Code Example

Below is a Flutter application for getting the mime type of a local file or a URL.

  import 'package:flutter/material.dart';
  import 'package:http/http.dart' as http;
  import 'package:mime/mime.dart';
  
  void main() => runApp(const MyApp());
  
  class MyApp extends StatelessWidget {
  
    const MyApp({Key? key}) : super(key: key);
  
    @override
    Widget build(BuildContext context) {
      return const MaterialApp(
        title: 'Woolha.com Flutter Tutorial',
        home: GetMimeTypeExample(),
      );
    }
  }
  
  class GetMimeTypeExample extends StatefulWidget {
  
    const GetMimeTypeExample({Key? key}) : super(key: key);
  
    @override
    State<StatefulWidget> createState() {
      return _GetMimeTypeExampleState();
    }
  
  }
  
  class _GetMimeTypeExampleState extends State<GetMimeTypeExample> {
  
    final TextEditingController _textEditingController = TextEditingController();
    String? _result;
  
    String? _getFileMimeType(String path) {
      return lookupMimeType(path);
    }
  
    Future<String?> _getUrlMimeType(String url) async {
      final response = await http.head(Uri.parse(url));
  
      return response.headers['content-type'];
    }
  
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          title: const Text('Woolha.com Flutter Tutorial'),
          backgroundColor: Colors.teal,
        ),
        body: SingleChildScrollView(
          padding: const EdgeInsets.all(15.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextField(
                controller: _textEditingController,
                decoration: const InputDecoration(
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.all(Radius.circular(5.0)),
                  ),
                  hintText: 'Enter path or URL',
                ),
              ),
              OutlinedButton(
                onPressed: () async {
                  final mimeType = _getFileMimeType(_textEditingController.text);
  
                  setState(() {
                    _result = mimeType;
                  });
                },
                child: const Text('Get file mime type', style: TextStyle(color: Colors.teal)),
              ),
              OutlinedButton(
                onPressed: () async {
                  final mimeType = await _getUrlMimeType(_textEditingController.text);
  
                  setState(() {
                    _result = mimeType;
                  });
                },
                child: const Text('Get URL mime type', style: TextStyle(color: Colors.teal)),
              ),
              Text('Result: ${_result ?? '-'}', style: const TextStyle(color: Colors.teal)),
            ],
          ),
        ),
      );
    }
  }

Summary

To get the mime type of a local file using Dart, you can use the lookupMimeType method of the mime package. For the mime type of a URL, you can make a HEAD request and read the value of content-type header from the response.