我正在运行 Ruby on Rails 3 和 Prototype,并且我想在为 file_field
选择文件时检查文件扩展名,因此如果它不是以下错误之一,我可以显示错误允许(在我的例子中,只有 .doc
和 .pdf
是允许的扩展名)。
此时,在我的 View 文件中,我以这种方式观察 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
中的字符串是否具有扩展名 .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= ........
}
关于javascript - 使用 Ruby on Rails 检查选择文件时的文件扩展名 'file_field' 并显示错误消息(如果有),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4966918/