一. 判斷文件類型一般可采用兩種方式
1. 后綴名判斷
簡單易操作,但無法准確判斷類型
2. 文件頭信息判斷
通常可以判斷文件類型,但有些文件類型無法判斷(如word和excel頭信息的前幾個字節是一樣的,無法判斷)
3. 使用apache.tika可輕松解決以上兩種方式存在的問題
二. 使用方式
1. maven依賴
<dependency> <groupId>org.apache.tika</groupId> <artifactId>tika-core</artifactId> <version>1.22</version> </dependency>
2. 具體實現
1 public static String getMimeType(InputStream inputStream){ 2 AutoDetectParser parser = new AutoDetectParser(); 3 parser.setParsers(new HashMap<MediaType, Parser>()); 4 5 Metadata metadata = new Metadata(); 6 7 try { 8 parser.parse(inputStream, new DefaultHandler(), metadata, new ParseContext()); 9 inputStream.close(); 10 } catch (TikaException | SAXException | IOException e) { 11 e.printStackTrace(); 12 } 13 14 return metadata.get(HttpHeaders.CONTENT_TYPE); 15 }
3. 常見文件類型
MimeType | 文件類型 |
---|---|
application/msword | word(.doc) |
application/vnd.ms-powerpoint | powerpoint(.ppt) |
application/vnd.ms-excel | excel(.xls) |
application/vnd.openxmlformats-officedocument.wordprocessingml.document | word(.docx) |
application/vnd.openxmlformats-officedocument.presentationml.presentation | powerpoint(.pptx) |
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet | excel(.xlsx) |
application/x-rar-compressed | rar |
application/zip | zip |
application/pdf | |
video/* | 視頻文件 |
image/* | 圖片文件 |
text/plain | 純文本 |
text/css | css文件 |
text/html | html文件 |
text/x-java-source | java源代碼 |
text/x-csrc | c源代碼 |
text/x-c++src | c++源代碼 |