如何访问使用Paperclip / Ruby on Rails上传的文件的原始内容?

我正在使用Paperclip / S3进行文件上传。 我上传文本类文件(不是.txt,但它们本质上是.txt)。 在show controller中,我希望能够获取上载文件的内容,但不要将内容视为其属性之一。 我能在这做什么?

attachment_file_name: "test.md", attachment_content_type: "application/octet-stream", attachment_file_size: 58, attachment_updated_at: "2011-06-22 01:01:40" 

PS – 似乎所有Paperclip教程都是关于图像,而不是文本文件。

以下是我访问附件的原始内容的方法:

 class Document has_attached_file :revision def revision_contents revision.copy_to_local_file.read end end 

请注意,我省略了我的回形针配置选项和任何类型的error handling。

在Paperclip 3.0.1中,您可以使用不需要写入(并从中删除)本地文件系统的io_adapter

 Paperclip.io_adapters.for(attachment.file).read 

要访问该文件,您可以使用路径方法: csv_file.path http://rdoc.info/gems/paperclip/Paperclip/Attachment#path-instance_method

这可以与例如CSV阅读器一起使用。

@ jon-m答案需要更新以反映回形针的最新变化,为了使其工作需要改变为:

 class Document has_attached_file :revision def revision_contents(path = 'tmp/tmp.any') revision.copy_to_local_file :original, path File.open(path).read end end 

有点令人费解的@jwadsa​​ck提到使用Paperclip.io_adapters.for方法完成同样的事情,似乎是一个更好,更清洁的方式来做这个恕我直言。

在显示文件之前,您需要将文件的内容(使用Rubys File.open)加载到变量中。 如果您的应用程序获得大量使用,这可能是一项昂贵的操作,因此在上载文件后阅读文件内容并将其放入数据库的文本列可能是值得的。

附件已经从IOStreaminheritance。 http://rdoc.info/github/thoughtbot/paperclip/master/Paperclip/Attachment

所以它应该只是"#{attachment}"<% RDiscount.new(attachment).to_html %>send_data(attachment) 。 但是,您想要显示数据。