选择’file_field’文件时检查文件扩展名,并使用Ruby on Rails显示错误消息(如果有)
我正在运行Ruby on Rails 3和Prototype,我想在为file_field
选择文件时检查文件扩展名,所以如果它不是允许的那个(我的情况下只有.doc
和.pdf
,我可以显示错误.pdf
是允许的扩展名)。
此时在我的视图文件中,我以这种方式观察file_field
:
page.event.observe('file_field_id', 'change') do |element| # Here I would like to put some code in order to check the file extension # If the file extension isn't '.doc' or '.pdf' I would like to set and show an error text in the 'error_id' # I know using 'element[:error_id].show' I can show the error, but... # 1. how to set the error value? # 2. how to check the file extension? end
现在,我需要检查在选择文件后, file_field
的字符串file_field
具有exdtion .doc
或.pdf
,如果不是,请设置error_id
的值并显示它。
我怎么能这样做?
更新 :我需要使用Protoype
框架。 可能吗?
在JS中,通过使用正则表达式,您可以获得文件扩展名。
var extens=(/[.]/.exec(myfile)) ? /[^.]+$/.exec(myfile) : undefined;
这里myfile
是文件的地址或路径。 这只是在“。”之后获取字符串的一部分。 。 然后你可以用if
进行一些控制检查。 就像是 :
if(extens=="doc" || extens=="pdf") { //your method goes here } else { error_id= ........ }