gpt4 book ai didi

java - 如何获取正在上传的文件的 InputStream 的 MIME 类型?

转载 作者:IT老高 更新时间:2023-10-28 20:23:25 41 4
gpt4 key购买 nike

简单问题:对于用户上传到我的 servlet 的文件,如何在不保存文件的情况下获取 InputStream 的 MIME 类型(或内容类型)?

最佳答案

我为 byte[] 编写了自己的内容类型检测器,因为上面的库不适合或者我无权访问它们。希望这可以帮助某人。

// retrieve file as byte[]
byte[] b = odHit.retrieve( "" );

// copy top 32 bytes and pass to the guessMimeType(byte[]) funciton
byte[] topOfStream = new byte[32];
System.arraycopy(b, 0, topOfStream, 0, topOfStream.length);
String mimeGuess = guessMimeType(topOfStream);

...

private static String guessMimeType(byte[] topOfStream) {

String mimeType = null;
Properties magicmimes = new Properties();
FileInputStream in = null;

// Read in the magicmimes.properties file (e.g. of file listed below)
try {
in = new FileInputStream( "magicmimes.properties" );
magicmimes.load(in);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

// loop over each file signature, if a match is found, return mime type
for ( Enumeration keys = magicmimes.keys(); keys.hasMoreElements(); ) {
String key = (String) keys.nextElement();
byte[] sample = new byte[key.length()];
System.arraycopy(topOfStream, 0, sample, 0, sample.length);
if( key.equals( new String(sample) )){
mimeType = magicmimes.getProperty(key);
System.out.println("Mime Found! "+ mimeType);
break;
} else {
System.out.println("trying "+key+" == "+new String(sample));
}
}

return mimeType;
}

magicmimes.properties 文件示例(不确定这些签名是否正确,但它们适用于我的用途)

# SignatureKey                  content/type
\u0000\u201E\u00f1\u00d9 text/plain
\u0025\u0050\u0044\u0046 application/pdf
%PDF application/pdf
\u0042\u004d image/bmp
GIF8 image/gif
\u0047\u0049\u0046\u0038 image/gif
\u0049\u0049\u004D\u004D image/tiff
\u0089\u0050\u004e\u0047 image/png
\u00ff\u00d8\u00ff\u00e0 image/jpg

关于java - 如何获取正在上传的文件的 InputStream 的 MIME 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4602060/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com