0

Suppose users can upload files, I want to find the extension of the uploaded file. Even if the user has renamed the extension of the file, I want to find the real extension of that file by it's header or bytecode..etc.

Please help me with a solution.

Note: Not just the extension by substring() or getContentType() but the real file extension, say for example(in windows), its a .doc file and user renames it to .jpg and uploads it. Its possible in php, but I don't know how to do that in java! but it can be done. Thank you.

sdolgy
  • 6,963
  • 3
  • 41
  • 61
Ashok Raj
  • 444
  • 6
  • 25

2 Answers2

0

Apache Commons: FileUpload is a good place to start. further, you could look at the link i referenced: JSP: Get MIME Type on File Upload for hints on how to do this.

As the user states in their question, the thought is if i rename a .png to a .jpg this will fool the getContentType() into thinking it's now a .jpg file. A quick search on google provided the following answer result: Get the mime type from a file that lists 3 very good options:

  1. Apache Tika

    The Apache Tika™ toolkit detects and extracts metadata and structured text content from various documents using existing parser libraries

  2. JMimeMagic

    jMimeMagic is a Java library for determining the MIME type of files or streams

  3. A java library that claims to help you with this, is: mime-util

    Enable Java programs to detect MIME types based on file extensions, magic data and content sniffing. Supports detection from java.io.File, java.io.InputStream, java.net.URL and byte arrays.

Community
  • 1
  • 1
sdolgy
  • 6,963
  • 3
  • 41
  • 61
0

A quick search brought this post up: http://fredeaker.blogspot.com/2006/12/file-type-mime-detection.html

The post lists several "magic" libraries that can detect the file type based on its contents.

casablanca
  • 69,683
  • 7
  • 133
  • 150