如何使用Java从文件中获得媒体类型(MIME类型)?到目前为止,我已经尝试了JMimeMagic和Mime-Util。第一个给了我内存异常,第二个没有正确地关闭它的流。
您将如何探测该文件以确定其实际类型(而不仅仅是基于扩展名)?
如何使用Java从文件中获得媒体类型(MIME类型)?到目前为止,我已经尝试了JMimeMagic和Mime-Util。第一个给了我内存异常,第二个没有正确地关闭它的流。
您将如何探测该文件以确定其实际类型(而不仅仅是基于扩展名)?
当前回答
如果你正在使用Servlet并且Servlet上下文对你可用,你可以使用:
getServletContext().getMimeType( fileName );
其他回答
MultipartFile文件;
org.springframework.web.multipart.MultipartFile
文件。getContentType ();
File file = new File(PropertiesReader.FILE_PATH);
MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();
String mimeType = fileTypeMap.getContentType(file);
URLConnection uconnection = file.toURL().openConnection();
mimeType = uconnection.getContentType();
我只是想知道大多数人如何从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();
}
我用下面的代码做到了。
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MimeFileType {
public static void main(String args[]){
try{
URL url = new URL ("https://www.url.com.pdf");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
InputStream content = (InputStream)connection.getInputStream();
connection.getHeaderField("Content-Type");
System.out.println("Content-Type "+ connection.getHeaderField("Content-Type"));
BufferedReader in = new BufferedReader (new InputStreamReader(content));
}catch (Exception e){
}
}
}
从roseindia:
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String mimeType = fileNameMap.getContentTypeFor("alert.gif");