如何使用Java从文件中获得媒体类型(MIME类型)?到目前为止,我已经尝试了JMimeMagic和Mime-Util。第一个给了我内存异常,第二个没有正确地关闭它的流。

您将如何探测该文件以确定其实际类型(而不仅仅是基于扩展名)?


当前回答

我找不到任何东西来检查视频/mp4 MIME类型,所以我做了自己的解决方案。 我偶然发现维基百科是错误的,并且00 00 00 18 66 74 79 70 69 73 6F 6D文件签名是不正确的。第四个字节(18)和所有70个字节(不包括)在其他有效的mp4文件中进行了相当多的更改后。

这段代码本质上是URLConnection的复制/粘贴。guessContentTypeFromStream代码,但为视频/mp4量身定制。

BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(content));
String mimeType = URLConnection.guessContentTypeFromStream(bis);

// Goes full barbaric and processes the bytes manually
if (mimeType == null){
    // These ints converted in hex ar:
    // 00 00 00 18 66 74 79 70 69 73 6F 6D
    // which are the file signature (magic bytes) for .mp4 files
    // from https://www.wikiwand.com/en/List_of_file_signatures
    // just ctrl+f "mp4"
    int[] mp4_sig = {0, 0, 0, 24, 102, 116, 121, 112};

    bis.reset();
    bis.mark(16);
    int[] firstBytes = new int[8];
    for (int i = 0; i < 8; i++) {
        firstBytes[i] = bis.read();
    }
    // This byte doesn't matter for the file signature and changes
    mp4_sig[3] = content[3];

    bis.reset();
    if (Arrays.equals(firstBytes, mp4_sig)){
        mimeType = "video/mp4";
    }
}

成功测试了10个不同的.mp4文件。

编辑:这是一个有用的链接(如果它仍然在线),在那里你可以找到许多类型的样本。我没有这些视频,也不知道谁有,但它们对测试上面的代码很有用。

其他回答

如果你在linux操作系统上工作,有一个命令行文件——mimetype:

String mimetype(file){

   //1. run cmd
   Object cmd=Runtime.getRuntime().exec("file --mime-type "+file);

   //2 get output of cmd , then 
    //3. parse mimetype
    if(output){return output.split(":")[1].trim(); }
    return "";
}

Then

mimetype("/home/nyapp.war") //  'application/zip'

mimetype("/var/www/ggg/au.mp3") //  'audio/mp3'

我只是想知道大多数人如何从Java文件中获取mime类型?

我已经发布了我的SimpleMagic Java包,它允许从文件和字节数组中确定内容类型(mime类型)。它被设计用来读取和运行Unix文件(1)命令魔法文件,这些文件是大多数~Unix操作系统配置的一部分。

我尝试了Apache Tika,但它很大,有大量的依赖关系,URLConnection不使用文件的字节,MimetypesFileTypeMap也只查看文件名。

使用SimpleMagic,你可以做以下事情:

// create a magic utility using the internal magic file
ContentInfoUtil util = new ContentInfoUtil();
// if you want to use a different config file(s), you can load them by hand:
// ContentInfoUtil util = new ContentInfoUtil("/etc/magic");
...
ContentInfo info = util.findMatch("/tmp/upload.tmp");
// or
ContentInfo info = util.findMatch(inputStream);
// or
ContentInfo info = util.findMatch(contentByteArray);

// null if no match
if (info != null) {
   String mimeType = info.getMimeType();
}

只需一行即可:MimetypesFileTypeMap()。getContentType(新文件(“请”))。查看完整的测试代码(Java 7):

import java.io.File;
import javax.activation.MimetypesFileTypeMap;
public class MimeTest {
    public static void main(String a[]){
         System.out.println(new MimetypesFileTypeMap().getContentType(
           new File("/path/filename.txt")));
    }
}

这段代码产生以下输出:文本/纯文本

JAF API是JDK 6的一部分。看看javax。激活包。

最有趣的类是javax.activation.MimeType -一个实际的MIME类型holder -和javax.activation.MimetypesFileTypeMap -类,其实例可以将文件的MIME类型解析为字符串:

String fileName = "/path/to/file";
MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();

// only by file name
String mimeType = mimeTypesMap.getContentType(fileName);

// or by actual File instance
File file = new File(fileName);
mimeType = mimeTypesMap.getContentType(file);

最好使用两层验证文件上传。

首先,您可以检查mimeType并验证它。

其次,您应该考虑将文件的前4个字节转换为十六进制,然后将其与神奇的数字进行比较。然后,这将是一种非常安全的检查文件验证的方法。