Mat*_*usz 7 ruby-on-rails stream paperclip
我想存储收到的电子邮件附件以及回形针的使用.从电子邮件我得到part.body,我不知道如何把它放到回形针模型.现在我创建临时文件并将port.body写入其中,将此文件存储到paperclip,然后删除文件.以下是我使用临时文件的方法:
l_file = File.open(l_path, "w+b", 0644)
l_file.write(part.body)
oAsset = Asset.new(
:email_id => email.id,
:asset => l_file,
:header => h,
:original_file_name => o,
:hash => h)
oAsset.save
l_file.close
File.delete(l_path)
Run Code Online (Sandbox Code Playgroud)
:asset是我的'has_attached_file'字段.有没有办法省略文件创建,并在Asset.new中执行类似:: asset => part.body的操作?
Dav*_*low 22
假设您使用mail gem来阅读电子邮件,我就是这样做的.你需要整个电子邮件'part',而不仅仅是part.body
file = StringIO.new(part.body) #mimic a real upload file
file.class.class_eval { attr_accessor :original_filename, :content_type } #add attr's that paperclip needs
file.original_filename = part.filename #assign filename in way that paperclip likes
file.content_type = part.mime_type # you could set this manually aswell if needed e.g 'application/pdf'
Run Code Online (Sandbox Code Playgroud)
现在只需使用文件对象保存到Paperclip关联.
a = Asset.new
a.asset = file
a.save!
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
Barlow的答案很好,但它实际上是猴子修补StringIO类.在我的情况下,我正在使用Mechanize :: Download#body_io,我不想污染这个类导致在应用程序中突然出现的意外错误.所以我在实例元类上定义方法如下:
original_filename = "whatever.pdf" # Set local variables for the closure below
content_type = "application/pdf"
file = StringIO.new(part.body)
metaclass = class << file; self; end
metaclass.class_eval do
define_method(:original_filename) { original_filename }
define_method(:content_type) { content_type }
end
Run Code Online (Sandbox Code Playgroud)
小智 6
我非常喜欢gtd的答案,但它可以更简单.
file = StringIO.new(part.body)
class << file
define_method(:original_filename) { "whatever.pdf" }
define_method(:content_type) { "application/pdf" }
end
Run Code Online (Sandbox Code Playgroud)
实际上并不需要将"元类"提取到局部变量中,只需将一些类附加到对象上即可.
| 归档时间: |
|
| 查看次数: |
5319 次 |
| 最近记录: |