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
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
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
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'
If the filename contains extension then use below code :
import 'package:mime/mime.dart';
File file = getFile(); // use any filepicker
final mimeType = lookupMimeType(file.path);
if the filename doesn't have an extension then use :
var dataHeader = await file.readAsBytes();
mimeType = lookupMimeType(file.path, headerBytes: dataHeader);
Full code :
String? mimeType = lookupMimeType(file!.path);
if(mimeType == null) {
var dataHeader = await file.readAsBytes();
mimeType = lookupMimeType(file!.path, headerBytes: dataHeader);
}