Get the Mime Type from a File

原文:http://www.rgagnon.com/javadetails/java-0487.html

Using javax.activation.MimetypesFileTypeMap

activation.jar is required, it can be downloaded from http://java.sun.com/products/javabeans/glasgow/jaf.html.

The MimetypesFileMap class is used to map a File to a Mime Type. Mime types supported are defined in a ressource file inside the activation.jar.

import javax.activation.MimetypesFileTypeMap;
import java.io.File;

class GetMimeType {
  public static void main(String args[]) {
    File f = new File("gumby.gif");
    System.out.println("Mime Type of " + f.getName() + " is " +
                         new MimetypesFileTypeMap().getContentType(f));
    // expected output :
    // "Mime Type of gumby.gif is image/gif"
  }
}

The built-in mime-type list is very limited but a mechanism is available to add very easily more Mime Types/extensions.

The MimetypesFileTypeMap looks in various places in the user's system for MIME types file entries. When requests are made to search for MIME types in the MimetypesFileTypeMap, it
searches MIME types files in the following order:

  1. Programmatically added entries to the MimetypesFileTypeMap instance.
  2. The file .mime.types in the user's home directory.
  3. The file <java.home>/lib/mime.types.
  4. The file or resources named META-INF/mime.types.
  5. The file or resource named META-INF/mimetypes.default (usually found only in the activation.jar file).

This method is interesting when you need to deal with incoming files with the filenames normalized. The result is very fast because only the extension is used to guess the nature
of a given file.

Using java.net.URL

Warning : this method is very slow!.

Like the above method a match is done with the extension. The mapping between the extension and the mime-type is defined in the file [jre_home]\lib\content-types.properties

import java.net.*;

public class FileUtils{
  public static String getMimeType(String fileUrl)
    throws java.io.IOException, MalformedURLException
  {
    String type = null;
    URL u = new URL(fileUrl);
    URLConnection uc = null;
    uc = u.openConnection();
    type = uc.getContentType();
    return type;
  }

  public static void main(String args[]) throws Exception {
    System.out.println(FileUtils.getMimeType("file://c:/temp/test.TXT"));
    // output :  text/plain
  }
}

A note from R. Lovelock :

I was trying to find the best way of getting the mime type of a file
and found your sight very useful. However I have now found a way of
getting the mime type using URLConnection that isn't as slow as the
way you describe.
import java.net.FileNameMap;
import java.net.URLConnection;

public class FileUtils {

  public static String getMimeType(String fileUrl)
      throws java.io.IOException
    {
      FileNameMap fileNameMap = URLConnection.getFileNameMap();
      String type = fileNameMap.getContentTypeFor(fileUrl);

      return type;
    }

    public static void main(String args[]) throws Exception {
      System.out.println(FileUtils.getMimeType("file://c:/temp/test.TXT"));
      // output :  text/plain
    }
  }

Using Apache Tika

Tika is subproject of Lucene, a search engine. It is a toolkit for detecting and extracting
metadata and structured text content from various documents using existing parser libraries.

This package is very up-to-date regarding the filetypes supported, Office 2007 formats are supported (docs/pptx/xlsx/etc...).

Apache Tika

Tika has a lot of dependencies ... almost 20 jars ! But it can do a lot more than detecting filetype. For example, you can parse a PDF or DOC to extract the text and the metadata
very easily.

import java.io.File;
import java.io.FileInputStream;

import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.ContentHandler;

public class Main {

    public static void main(String args[]) throws Exception {

    FileInputStream is = null;
    try {
      File f = new File("C:/Temp/mime/test.docx");
      is = new FileInputStream(f);

      ContentHandler contenthandler = new BodyContentHandler();
      Metadata metadata = new Metadata();
      metadata.set(Metadata.RESOURCE_NAME_KEY, f.getName());
      Parser parser = new AutoDetectParser();
      // OOXMLParser parser = new OOXMLParser();
      parser.parse(is, contenthandler, metadata);
      System.out.println("Mime: " + metadata.get(Metadata.CONTENT_TYPE));
      System.out.println("Title: " + metadata.get(Metadata.TITLE));
      System.out.println("Author: " + metadata.get(Metadata.AUTHOR));
      System.out.println("content: " + contenthandler.toString());
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    finally {
        if (is != null) is.close();
    }
  }
}

You can download here a
ZIP containing the required jars if you want to check it out.

Using JMimeMagic

Checking the file extension is not a very strong way to determine the file type. A more robust solution is possible with theJMimeMagic
library
. JMimeMagic is a Java library (LGLP licence) that retrieves file and stream mime types by checking magic headers.

// snippet for JMimeMagic lib
//     http://sourceforge.net/projects/jmimemagic/

Magic parser = new Magic() ;
// getMagicMatch accepts Files or byte[],
// which is nice if you want to test streams
MagicMatch match = parser.getMagicMatch(new File("gumby.gif"));
System.out.println(match.getMimeType()) ;

Thanks to Jean-Marc Autexier and sygsix for the tip!

Using mime-util

Another tool is mime-util.
This tool can detect using the file extension or the magic header technique.

import eu.medsea.mimeutil.MimeUtil;

public class Main {
    public static void main(String[] args) {
        MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
        File f = new File ("c:/temp/mime/test.doc");
        Collection<?> mimeTypes = MimeUtil.getMimeTypes(f);
        System.out.println(mimeTypes);
        //  output : application/msword
    }
}

The nice thing about mime-util is that it is very lightweight. Only 1 dependency with slf4j

Using Droid

DROID (Digital Record Object Identification) is a software tool to perform automated batch identification of file formats.

DROID uses internal and external signatures to identify and report the specific file format versions of digital files. These signatures are stored in an XML signature file, generated
from information recorded in the PRONOM technical registry. New and updated signatures are regularly added to PRONOM, and DROID can be configured to automatically download updated signature files from the PRONOM website via web services.

It can be invoked from two interfaces, a Java Swing GUI or a command line interface.

http://droid.sourceforge.net/wiki/index.php/Introduction

Aperture framework

Aperture is an open source library and framework for crawling and indexing information sources such as file systems, websites and mail boxes.

The Aperture code consists of a number of related but independently usable parts:

  • Crawling of information sources: file systems, websites, mail boxes
  • MIME type identification
  • Full-text and metadata extraction of various file formats
  • Opening of crawled resources

For each of these parts, a set of APIs has been developed and a number of implementations is provided.

http://aperture.wiki.sourceforge.net/Overview

ps:

If you're an Android developer, you can use a utility class android.webkit.MimeTypeMap which
maps MIME-types to file extensions and vice versa.

Following code snippet may help you.

private static String getMimeType(String fileUrl) {
    String extension = MimeTypeMap.getFileExtensionFromUrl(fileUrl);
    return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
时间: 2024-08-31 12:02:17

Get the Mime Type from a File的相关文章

MIME Type 引出的两难困境

mime 一切从一个糟糕的浏览器开始,它完全不支持 XHTML. 什么是 MIME Type? 为什么这么说呢?首先,我们要了解浏览器是如何处理内容的.在浏览器中显示的内容有 HTML.有 XML.有 GIF.还有 Flash--那么,浏览器是如何区分它们,绝对什么内容用什么形式来显示呢?答案是 MIME Type,也就是该资源的媒体类型. 媒体类型通常是通过 HTTP 协议,由 Web 服务器告知浏览器的,更准确地说,是通过 Content-Type 来表示的,例如: Content-Type

jsp问题-jsp如何获取页面&amp;amp;lt;input type=&amp;amp;quot;file&amp;amp;quot; /&amp;amp;gt;里面的路径

问题描述 jsp如何获取页面<input type="file" />里面的路径 jsp如何获取页面里面的路径 解决方案 页面里面的路径?不懂你的问题....

&amp;amp;lt;input type=&amp;amp;quot;file&amp;amp;quot;&amp;amp;gt; 的传值问题

问题描述 <html><head><script> function ss(){ var file=document.getElementById("a").value; document.getElementById("b").value=file; alert(document.getElementById("b").value); }</script></head><body

手机网站上传图片-在手机网站内上传图片,使用 input type=&amp;amp;quot;file&amp;amp;quot; 的问题,不同手机浏览器效果不同。

问题描述 在手机网站内上传图片,使用 input type="file" 的问题,不同手机浏览器效果不同. 在手机端浏览器,测试opera.QQ.小米原生.安卓原生.iPhone原生.UC.(微信内应该是调用默认浏览器内核.) 只有QQ.UC和iPhone的浏览器正常执行,我用的 jQuery-File-Upload ,QQ和iPhone可以多选,UC只能一张张的单选. 其他浏览器再选中文件后,会打开一个新页面,之前父页面会刷新. 之所以没用微信内置调用图片的,因为我要传的图比较多.

java web-jQuery获取&amp;amp;lt;input type=&amp;amp;quot;file&amp;amp;quot;&amp;amp;gt;的绝对路径获取不到

问题描述 jQuery获取<input type="file">的绝对路径获取不到 想在选择文件之后标签里预览一下的,但是路径获取不到查看资料说是安全性的问题,如果是这样,应该怎么解决?怎么才能获取路径. 解决方案 图片预览看这个:javascript客户端图片预览 获取客户端路径没意思而且安全范围外,获取不到 解决方案二: js/jquery 获取本地文件的文件路劲 获取input框中type='file' 中的文件路径 解决方案三: 使用HTML5的FileReader

ajax-html input type=&amp;amp;#39;file&amp;amp;#39; 我选择了文件 怎么把他传给后台

问题描述 html input type='file' 我选择了文件 怎么把他传给后台 我是选了之后按确定按钮图片说明 就相当于这种当我按了确定按钮时,用ajax提交到后台,(比如说我选的是图片)转为byte类型的传到后台 就像我 提这个问题的时候选照片的那个功能 解决方案 由于浏览器的安全性,前台好像无法获取文件的路径了,只能获取文件名.用submit提交吧 解决方案二: html自定义input type='file'样式 解决方案三: 你问题说的用ajax提交是把file表单作为请求参数提

java-如何获取&amp;amp;lt;input type=&amp;amp;quot;file&amp;amp;quot; /&amp;amp;gt; 文件的路径?

问题描述 如何获取<input type="file" /> 文件的路径? 我要做一个java 的excel 文件导入功能, 需要获取一个文件的路径,如何选择后获取文件路径? 解决方案 不需要获取客户端的路径,文件是通过流传到后台的,后台接受后按照自己定义的规则存放到了服务器, 需要下载此文件的时候,也是根据规则从服务器上获取文件,然后通过流传到浏览器的. 解决方案二: java web 有文件上传的组件可以直接用的,如果你是file类型的表单,就能获取文件的输入流信息.文

javascript怎么获取&amp;amp;lt;input type=&amp;amp;quot;file&amp;amp;quot; /&amp;amp;gt; 文件的路径

问题描述 javascript怎么获取<input type="file" /> 文件的路径 javascript怎么获取 文件的路径:或者在servlet里面获取到file的路径也行,求大神解救啊! 解决方案 IE8以上设置:工具 -> Internet选项 -> 安全 -> 自定义级别 -> 找到"其他"中的"将本地文件上载至服务器时包含本地目录网络生活网径",选中"启用"即可或者Ser

&amp;amp;lt;input type=&amp;amp;quot;file&amp;amp;quot; &amp;amp;gt;如何实现上传文件到服务器

问题描述 <input type="file" >如何实现上传文件到服务器 <form method="post" enctype="multipart/form-data" id="UpLoad"> <div> <input type="file" id="upFile" name="upFile"> </div