I have moved!
My new blog is at lindsaar.net
All the old content will stay here though. But check out the new blog
¿ 11/6/2007 - Ruby on Rails file content validation
Sometimes you need to know that the file that your users are uploading is of the correct content. But how can you do this before you accept the file?
Well... in rails... easy when you know how.
Basically all you need to do is in the model you are working in, add a method called "validate". Within this method you can call errors.add_to_base 'message' if a validation fails.
For example, to make sure a file is a Microsoft Word HTML saved document, the following would work:
def validate if self.file word = Regexp.new('schemas-microsoft-com:office:word') utf_charset = Regexp.new(/content=.*?charset=utf-8/) uploaded_file = File.new(self.file, "r") if !(uploaded_file.read.chars.to_s =~ word) errors.add_to_base "The file must be a MS word HTML document" elsif !(uploaded_file.read.chars.to_s =~ utf_charset) errors.add_to_base "The file must use the UTF-8 character set" end end end
I am sure it could be a bit more DRY... but there you go! Enjoy!
blogLater
Mikel |
Post A Comment! :: Send to a Friend!
|
|
|
|
About Me
AKA Raasdnil, this site is about web coding, hosting and all other matters that relate to this... especially Ruby on Rails!
Links
|
|