AnA*_*ice 2 ruby-on-rails paperclip mongodb ruby-on-rails-3
我正在使用带有Paperclip + Rails的Rails 3:
Gemfile
gem "paperclip"
gem "mongoid-paperclip", require: 'mongoid_paperclip'
Run Code Online (Sandbox Code Playgroud)
一切正常,除非用户上传带有非字母数字字符的文件的照片,如下所示:
thing 1/2/3/.PNG
Run Code Online (Sandbox Code Playgroud)
我试过用以下方法处理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
Run Code Online (Sandbox Code Playgroud)
但是,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:
Run Code Online (Sandbox Code Playgroud)
有关处理此错误的任何想法/建议?
谢谢
mongoid-paperclip gem只是将所有给定选项放到回形针上(参见来源),因此您需要清理文件名,就像使用普通回形针一样.
有两种方法可以实现此目的,这是默认值:
:restricted_characters => /[&$+,\/:;=?@<>\[\]\{\}\|\\\^~%# ]/,
:filename_cleaner => nil,
Run Code Online (Sandbox Code Playgroud)
通常,文本名称中的空格非常精细,但您可以尝试将其添加到文件名中:restricted_characters.限制字符用于初始化a PaperClip::FilenameCleaner.
has_mongoid_attached_file :image, restricted_characters: /[\s&$+,\/:;=?@<>\[\]\{\}\|\\\^~%# ]/
Run Code Online (Sandbox Code Playgroud)
您可以更明确地指定文件名清理程序,如下所示(但不确定是否相关).
has_mongoid_attached_file :image, filename_cleaner: Paperclip::FilenameCleaner.new(/[\s&$+,\/:;=?@<>\[\]\{\}\|\\\^~%# ]/)
Run Code Online (Sandbox Code Playgroud)
这与指定restricted_characters选项完全相同.但是,您可以使用此选项并将其交给您自己的版本FilenameClear.它应该有一个call方法,并将接收文件名作为参数(参见来源)