Get File file type

Reference blog:
org.apache.tika
--java uses tika to determine file type
http://blog.sina.com.cn/s/blog_958a07d001014184.html
--va various methods to obtain file type Mime Type
http:// dada89007.iteye.com/blog/1392606
--TIKA content extraction
http://www.yiibai.com/tika/tika_content_extraction.html
--The mime type of common files can be judged by mime+ suffix name
http://blog. csdn.net/kuangshp128/article/details/75207984
http://www.w3school.com.cn/media/media_mimeref.asp


import org.apache.tika.metadata.HttpHeaders;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaMetadataKeys;
import org.apache.tika.mime.MediaType;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
	/**
	 * Get the mime type of the file
	 * @param multipartFile - from spring-web-3.*.jar
	 * @return
	 */
   private String getFileMimeType(MultipartFile multipartFile) {
	    if (null == multipartFile) {
			logger.error("The file does not exist.");
			return "";
		}
        AutoDetectParser parser = new AutoDetectParser();
        parser.setParsers(new HashMap<MediaType, Parser>());
        Metadata metadata = new Metadata();
        metadata.add(TikaMetadataKeys.RESOURCE_NAME_KEY, multipartFile.getOriginalFilename());
        InputStream stream=null;
        try {
            stream = multipartFile.getInputStream();
            parser.parse(stream, new DefaultHandler(), metadata, new ParseContext());
        } catch (Exception e) {
            e.printStackTrace ();
        } finally {
        	//Close the stream in the finally block
        	try {
				stream.close();
			} catch (IOException e) {
				logger.info("Exception when InputStream is closed");
				e.printStackTrace ();
			}
		}
        return metadata.get(HttpHeaders.CONTENT_TYPE);
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326523153&siteId=291194637