Flutter: how to get magic numbers of file?

859 Views Asked by At

I'm using file_picker to choose file from storage and sometimes it doesn't give an extension but I need to know an extension to send it to server side. I'm going to identify it by Magic Number like this

  print(lookupMimeType('test.html', headerBytes: [0xFF, 0xD8]));
  // image/jpeg

but don't know how to get it. Giving whole path to lookupMimeType doesn't help because file_picker caches file without extension. Can you help how to solve or how to figure it out ?

P.S Sorry for my bad English

1

There are 1 best solutions below

0
frederico On

To get the file header bytes you can do this:

List<int> fileBytes = File('PATH_TO_YOUR_FILE').readAsBytesSync().toList();

List<int> header = [];

fileBytes.forEach((element){
    if(element == 0) return;
    header.add(element);
});

print(lookupMimeType('test.html', headerBytes: header));