permaculture playing cards*
The moose likes I/O and Streams and the fly likes FileUpload and File type Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "FileUpload and File type" Watch "FileUpload and File type" New topic
Author

FileUpload and File type

Lilian Chase
Greenhorn

Joined: Jun 14, 2010
Posts: 24
I wrote a servlet to do file upload using the commons jar. This part is working fine and I'm able to upload files successfully to the server.

My question is How do I determine the file type of each file? Users can upload files with any extensions as long as the content is text.

Eg,

The user can upload test1.txt, test2.abc, test3.fa, if all 3 files are text-based.
On the other hand, I want to stop the upload if the file is an image file, even if the filename is image.txt.


So, is there a way to check and validate the content of the file and determining the file type without restricting the file extensions?
Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2771
    
  10

It's sometimes possible to tell the type of a file based on its content. One way is to check the magic number, though not all file types have one, and there's no guarantee there won't be conflicts (though it's statistically improbable). For example, GIF files all start with the ASCII string GIF87a or GIF89a. A text file or pure binary file might also begin with this combination, but it's unlikely. Wikipedia will give you a place to start.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19552
    
  16

Except if it's a text file discussing the GIF89a format


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: FileUpload and File type
 
Similar Threads
PLGN0021E: Servlet Request Processor Exception
please help
Files upload problem with .dbf and .exe files
JSP that converts office extensions to pdf and then upload them
Uploading DBF files problem