如何从dart:html File对象的文件内容获取MIME类型
通过文件内容识别dart:html File对象的MIME类型
要绕过文件扩展名,基于实际内容判断dart:html的File对象MIME类型,核心思路是读取文件开头的魔数(文件签名)——这是不同文件类型内置的固定字节序列,比扩展名更可靠。
以下是具体实现代码:
import 'dart:html'; import 'dart:typed_data'; Future<String> detectMimeTypeByContent(File file) async { // 读取文件前8个字节,覆盖绝大多数常见文件的魔数长度 final reader = FileReader(); final blobSlice = file.slice(0, 8); reader.readAsArrayBuffer(blobSlice); await reader.onLoad.first; final headerBytes = Uint8List.fromList(reader.result as List<int>); // 匹配常见文件类型的魔数 if (headerBytes.length >= 2 && headerBytes[0] == 0xFF && headerBytes[1] == 0xD8) { return 'image/jpeg'; } else if (headerBytes.length >= 4 && headerBytes[0] == 0x89 && headerBytes[1] == 0x50 && headerBytes[2] == 0x4E && headerBytes[3] == 0x47) { return 'image/png'; } else if (headerBytes.length >= 3 && headerBytes[0] == 0x47 && headerBytes[1] == 0x49 && headerBytes[2] == 0x46) { return 'image/gif'; } else if (headerBytes.length >= 4 && headerBytes[0] == 0x25 && headerBytes[1] == 0x50 && headerBytes[2] == 0x44 && headerBytes[3] == 0x46) { return 'application/pdf'; } else if (headerBytes.length >= 2 && headerBytes[0] == 0x50 && headerBytes[1] == 0x4B) { // ZIP、DOCX、XLSX、PPTX等均基于ZIP格式,可根据需求进一步细化判断 return 'application/zip'; } // 未匹配到已知魔数时, fallback到文件自带的type属性(可能基于扩展名)或默认类型 return file.type.isNotEmpty ? file.type : 'application/octet-stream'; }
说明
- 魔数匹配规则可以根据需求扩展,比如添加MP4(开头字节
0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70)、SVG(开头为<?xml对应的字节序列)等类型的判断。 - 仅读取文件前几个字节,不会加载整个文件,性能开销极低。
内容的提问来源于stack exchange,提问作者Ryan Haining
相关产品推荐
相关产品推荐

