How can I get MIME type of an InputStream of a file that is being uploaded?

前端 未结 8 1383
离开以前
离开以前 2020-12-30 21:51

Simple question: how can I get MIME type (or content type) of an InputStream, without saving file, for a file that a user is uploading to my servlet?

8条回答
  •  甜味超标
    2020-12-30 22:09

    You can just add the tika-app-1.x.jar to your classpath as long as you don't use slf4j logging anywhere else because it will cause a collision. If you use tika to detect an inputstream it has to be mark supported. Otherwise, calling tika will erase your input stream. However if you use the apache IO library to get around this and just turn the InputStream into a File in memory.

    import org.apache.tika.*;
    
    Tike tika = new Tika();
    InputStream in = null;
    FileOutputStream out = null;
    try{
       out = new FileOutputStream(c:/tmp.tmp);
       IOUtils.copy(in, out);
       String mimeType = tika.detect(out);
    }catch(Exception e){
       System.err.println(e);
    } finally {
       if(null != in) 
           in.close();
       if(null != out)
           out.close();
     }
    

提交回复
热议问题