I have a upload text file field, and with it I plan to save the file somewhere and then store the location of the file in a database. However, I want to make sure the file they uploaded is a .txt file, and not, say, an image file. I imagine this happens in the validation step. How does one validate such a thing? Also, how do you get the filename of the uploaded file? I could always just check if it said '.txt' but for future reference knowing how to validate without just the filename would be helpful.
views:
192answers:
3The Solution for your problem is you can create a validates_format_of
and write the regular expression in order make sure the uploaded file is .txt format in your model file , example if its an Text model the Validation code would be
class Text < ActiveRecord::Base
validates_format_of :text_file ,:with => ^.*\.(txt)$, :on => :create
end
Above Code validates the format of the files it only uploads the file with Alphanumeric file name with .txt
files ,Any other format will through an error during uploading the file .
EDIT In order to check the Regular Expression you can test it using this tool Rubular
Hope this helps !
One way of doing it, the simple way really, would be to pass the file through an image loader, preferably one that handles multiple common formats, and see if it throws an error.
The other way is to manually check the file header for common image format headers. For example, .bmp files start with BM. Other formats have their own specific markings you can use.
Trying to validate the contents of a file based on the filename extension is opening the door for major hackerdom. It's trivial to change the extension and upload the file.
If you are on a Mac/Linux/Unix-based system the OS "file" command is the standard because it looks inside the file for key bytes that flag file types. http://en.wikipedia.org/wiki/File%5F%28Unix) I'm not sure what's available for Windows, but this might help: http://stackoverflow.com/questions/51572/determine-file-type-in-ruby