如何获取文件类型? [英] How to get type of file?

查看:103
本文介绍了如何获取文件类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图找到一个可以识别文件类型的软件包。例如

 最终路径= /some/path/to/file/file.jpg ; 

应被识别为图像,或者



<上课前= lang-dart prettyprint-override> 最终路径= /some/path/to/file/file.doc;

应被识别为文档

解决方案

您可以使用 mime ,以提取 MIME类型来自文件名:

  import'package:mime / mime。镖'; 

最终的mimeType = lookupMimeType(’/ some / path / to / file / file.jpg’); //'image / jpeg'



Helper函数



如果您想知道文件 path 是否表示图像,则可以创建如下函数:

  import'package:mime / mime.dart'; 

bool isImage(String path){
final mimeType = lookupMimeType(path);

return mimeType.startsWith(’image /’);
}

同样,如果您想知道路径代表文档,您可以编写如下函数:

 导入'package:mime / mime.dart'; 

bool isDocument(String path){
final mimeType = lookupMimeType(path);

return mimeType ==‘application / msword’;
}






您可以找到以下列表MIME类型 或查看 mime



来自文件头



使用 mime 包,甚至可以检查文件的头字节:

  final mimeType = lookupMimeType('image_without_extension',headerBytes:[0xFF,0xD8]); // jpeg 


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'

Helper functions

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.

From file headers

With the mime package, you can even check against header bytes of a file:

final mimeType = lookupMimeType('image_without_extension', headerBytes: [0xFF, 0xD8]); // jpeg

这篇关于如何获取文件类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆