使用apache.tika可輕鬆解決以上兩種方式存在的問題css
使用apache.tika判斷文件類型html
<!-- https://mvnrepository.com/artifact/org.apache.tika/tika-core --> <dependency> <groupId>org.apache.tika</groupId> <artifactId>tika-core</artifactId> <version>1.9</version> </dependency>
private static String getMimeType(File file) { if (file.isDirectory()) { return "the target is a directory"; } AutoDetectParser parser = new AutoDetectParser(); parser.setParsers(new HashMap<MediaType, Parser>()); Metadata metadata = new Metadata(); metadata.add(TikaMetadataKeys.RESOURCE_NAME_KEY, file.getName()); InputStream stream; try { stream = new FileInputStream(file); parser.parse(stream, new DefaultHandler(), metadata, new ParseContext()); stream.close(); } catch (TikaException | SAXException | IOException e) { e.printStackTrace(); } return metadata.get(HttpHeaders.CONTENT_TYPE); }
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++源代碼 |