根据文件后缀名获取对应的MIME类型的两种常见方式如下:
- JMimeMagic
该方式是通过检测magic headers来判断文件或者流的mime类型的java工具包。该插件在持续更新中,因此推荐使用。
a. 加入依赖
<dependency>
<groupId>net.sf.jmimemagic</groupId>
<artifactId>jmimemagic</artifactId>
<version>0.1.5</version>
</dependency>
b. 示例代码
public static void main(String[] args) throws MagicParseException, MagicException, MagicMatchNotFoundException {
File file = new File("C:\\Users\\liujiang\\Desktop\\JAVA10年技术栈.png");
MagicMatch matcher = Magic.getMagicMatch(file,false,true);
System.out.println(matcher.getMimeType());;
}
- java.net.URL
该方式是直接进行后缀名匹配,为JDK自带方法。
//fileRoute:文件URL路径
URL url = new URL("C:\\Users\\liujiang\\Desktop\\JAVA10年技术栈.png");
//通过URL的openStrean方法获取URL对象所表示的自愿字节输入流
InputStream is = url.openStream();
// 设置response参数,可以打开下载页面
response.reset();
String mimeType = URLConnection.getFileNameMap().getContentTypeFor(file.getName());
response.setContentType("" + mimeType + ";charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("utf-8"), "ISO8859-1"));
ServletOutputStream out = response.getOutputStream();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(out);
byte[] e = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(e, 0, e.length))) {
bos.write(e, 0, bytesRead);
}
} catch (IOException arg24) {
throw arg24;
} finally {
if (bis != null) {
bis.close();
}
}