【问题标题】:How get the last 4 letters of the name如何获取名称的最后 4 个字母
【发布时间】:2013-11-10 22:55:26
【问题描述】:

在 _form 中,我有一个用于上传文件的字段。 我要做的是检查文件是否包含危险的扩展名。

在我的情况下,如果扩展名是以下之一,我会返回一条错误消息: . '蝙蝠'。 '和'。 'EXE文件'。 'src',。 '命令'

所以我这样做了:

def suspitious_attachment        
  if ends_with? '.bat', '.com', '.exe', '.src', '.cmd'
    errors.add(:base, I18n.t('errors.messages.suspitious_attachment', :value => attachments.split(".").last))
  end
end

但这不是一个好主意,一个文件的名称中可以有多个点。

所以我想得到名字的最后 4 个字母。

我做不到,你能帮帮我吗?

对不起我的英语。

【问题讨论】:

  • 检查最后四个字母会有什么不同?

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1


【解决方案1】:

你在这里让自己陷入一种虚假的安全感。检查文件名不会阻止有人上传带有假扩展名的文件。

如果您需要验证文件格式,则应改为检查 MIME 类型。

在此处查看更多信息:How to check in rails uploaded file type?

【讨论】:

    【解决方案2】:

    您可以使用[-4..-1][-4, 4]

    'this.is.really.dangerous.file.exe'[-4..-1]
    # => ".exe"
    'this.is.really.dangerous.file.exe'[-4, 4]
    # => ".exe"
    'a_file.rb'[-4..-1]
    # => "e.rb"
    

    File::extname更适合获取文件名。

    File.extname 'a_file.cmd'
    # => ".cmd"
    File.extname 'a_file.rb'
    # => ".rb"
    File.extname 'this.is.really.dangerous.file.exe'
    # => ".exe"
    

    【讨论】:

      猜你喜欢
      • 2019-09-10
      • 2015-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多