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

前端 未结 8 1405
离开以前
离开以前 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

    I think this solves problem:

        public String readIt(InputStream is) {
        if (is != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
    
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
                is.close();
                return sb.toString();
        }
        return "error: ";
    }        
    

    What it returns? For example for png : "♦PNG\n\n♦♦♦.....", for xml:

    Quite usefull, You cant try string.contains() to check what is it

提交回复
热议问题