如何使用Rails回形针处理具有非字母数字字符的文件名

问题描述 投票:2回答:4

我正在将Rails 3与回形针+ Rails一起使用:

Gemfile
  gem "paperclip"
  gem "mongoid-paperclip", require: 'mongoid_paperclip'

除非用户上载带有非字母数字字符的文件名的照片,否则一切都会正常:

thing 1/2/3/.PNG

我尝试使用before_post_process before_validation:]处理此>

  def strip_strange_characters_from_attachments
    # Set the clean Attachment File Title
    self.attachment.instance.meta['file_name'] = "test.png"
  end

然而,Rails事先出现了错误,并且文件没有上传。错误如下。有什么想法吗?

[2014-06-10 13:54:47] INFO    Command :: identify -format %wx%h '/var/folders/g_/kythn1dx4fbbry5npb4jx1cr0000gn/T/thing 1:2:3:20140610-41978-ksy5e9.PNG[0]'
[2014-06-10 13:54:47] INFO    [paperclip] An error was received while processing: #<Paperclip::Errors::NotIdentifiedByImageMagickError: /var/folders/g_/kythn1dx4fbbry5npb4jx1cr0000gn/T/thing 1:2:3:20140610-41978-ksy5e9.PNG is not recognized by the 'identify' command.>
[2014-06-10 13:54:47] INFO    Command :: identify -format %wx%h '/var/folders/g_/kythn1dx4fbbry5npb4jx1cr0000gn/T/thing 1:2:3:20140610-41978-ksy5e9.PNG[0]'
[2014-06-10 13:54:47] INFO    [paperclip] An error was received while processing: #<Paperclip::Errors::NotIdentifiedByImageMagickError: /var/folders/g_/kythn1dx4fbbry5npb4jx1cr0000gn/T/thing 1:2:3:20140610-41978-ksy5e9.PNG is not recognized by the 'identify' command.>
[2014-06-10 13:54:47] INFO    Command :: identify -format %wx%h '/var/folders/g_/kythn1dx4fbbry5npb4jx1cr0000gn/T/thing 1:2:3:20140610-41978-ksy5e9.PNG[0]'
[2014-06-10 13:54:47] INFO    Completed 422 Unprocessable Entity in 120.0ms
[2014-06-10 13:54:48] INFO    Mongo: (1.5333ms) | Query count: 3
[2014-06-10 13:54:48] FATAL   
Mongoid::Errors::Validations - 
Problem:
  Validation of Mongo::Attachment failed.
Summary:
  The following errors were found: Attachment /var/folders/g_/kythn1dx4fbbry5npb4jx1cr0000gn/T/thing 1:2:3:20140610-41978-ksy5e9.PNG is not recognized by the 'identify' command., Attachment /var/folders/g_/kythn1dx4fbbry5npb4jx1cr0000gn/T/thing 1:2:3:20140610-41978-ksy5e9.PNG is not recognized by the 'identify' command.
Resolution:

关于处理此错误的任何想法/建议吗?

[我将Rails 3与回形针一起使用+ Rails:Gemfile gem“ paperclip” gem“ mongoid-paperclip”,要求:'mongoid_paperclip'一切正常,除非用户上传的文件名带有...

ruby-on-rails ruby-on-rails-3 mongodb paperclip
4个回答
7
投票

[Mongoid-paperclip宝石只是将所有给定的选项交给了回形针(请参阅source,因此您需要清除文件名,就像使用普通回形针时一样。

有两个选项可以完成此操作,这是默认值:


1
投票

查看您遇到的错误,似乎文件名

已修复。 /被替换为:

1
投票

我必须做类似的事情,并使用before_create和before_update进行处理,但这是使用常规的Paperclip gem进行的。没有显示randomize_file_name方法,但是您知道了。

before_create :randomize_attachment_name
before_update :randomize_attachment_name

def randomize_attachment_name
  if document_file_name
    random_name = randomize_file_name(document_file_name)
    self.document.instance_write(:file_name, random_name)
  end
end

-2
投票

为什么不仅仅用这样的东西改变路径?

path: '/:class/:attachment/:id_partition/:style/:id.:extension'
© www.soinside.com 2019 - 2024. All rights reserved.