检查的文件扩展名选择文件“的是,file_field”,并显示错误信息(如果有)使用Ruby on Rails的是、错误信息、文件扩展名、文件

2023-09-10 18:21:02 作者:姐比柠檬还萌比澳门还傲つ

我on Rails的3和样机运行Ruby和我想检查的文件扩展名上选择文件的的是,file_field ,这样我就可以显示一个错误,如果它是而不是那些被允许的之一(在我的情况下,仅的.doc 的.pdf 允许扩展)。

I am running Ruby on Rails 3 and Prototype and I would like to check the file extension on selecting a file for file_field, so I can show an error if it is not one of those that are permitted (in my case only .doc and .pdf are permitted extensions).

在这个时候,我认为文件I obseve的的是,file_field 以这种方式:

At this time in my view file I obseve the file_field in this way:

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 具有用Exention 的.doc 的.pdf ,如果没有,设置一个值 ERROR_ID 和表现出来。

Now I need to check if, after selecting a file, the string in the file_field have the exention .docor .pdf and if no, set a value for the error_id and show it.

我怎么能这样做?

更新:我需要使用 Protoype 框架。这可能吗?

UPDATE: I need that using the Protoype framework. Is it possible?

推荐答案

在JS,使用正前pression就可以得到文件的扩展名。

In JS, by using regular expression you can get file extension.

var extens=(/[.]/.exec(myfile)) ? /[^.]+$/.exec(myfile) : undefined;

下面 MYFILE 的地址或文件的路径。这只是发生后的字符串的一部分。 。然后,你可以放置一些控制检查与如果。是这样的:

Here myfileis the address or the path of the file. This simply takes the part of the string after "." . Then you can place some control checks with if. Something like :

if(extens=="doc" || extens=="pdf")
{
       //your method goes here
}
else
{
       error_id= ........
}