Ruby On Rails Spreadsheet - Validate File Type
I'm using the rails Spreadsheet gem (http://spreadsheet.rubyforge.org/GUIDE_txt.html) to import excel data into my application.
I can get the Excel file to upload fine and use:
book = Spreadsheet.open filePath
to open the file
This works fine if the file is a valid E开发者_如何转开发xcel file, but if my user decides to upload a random image file or something else instead, I get this error:
OLE2 signature is invalid
Which is understandable.
I can't find anywhere a way to validate the file before I open it. I'd rather not do it by file extension if I can help it, does anyone know a way to try to validate the file by content type before I open it?
Ta, Jo
There are a number of ways to validate the file type, most of them however are by checking the file extension.
If you don't want to do that and you have access to the 'file' command you can try this:
class File
def type_from_file_command
type = (self.original_filename.match(/\.(\w+)$/)[1] rescue "octet-stream").downcase
mime_type = `file -b --mime-type #{self.path}`.split(':').last.strip rescue "application/x-#{type}"
mime_type = "application/x-#{type}" if mime_type.match(/\(.*?\)/)
mime_type
end
end
ruby-1.9.2-p290 :030 > a = File.open("/path/nube_minilogo.psd")
=> #<File:/path/nube_minilogo.psd>
ruby-1.9.2-p290 :031 > a.type_from_file_command
=> "image/vnd.adobe.photoshop"
Adapted from Paperclip.
精彩评论