How do you access the raw content of a file uploaded with Paperclip / Ruby on Rails?

偶尔善良 提交于 2019-11-27 20:06:20

Here's how I access the raw contents of my attachment:

class Document

  has_attached_file :revision

  def revision_contents
    revision.copy_to_local_file.read
  end

end

Please note, I've omitted my paperclip configuration options and any sort of error handling.

In Paperclip 3.0.1 you could just use the io_adapter which doesn't require writing to (and removing from) the local file system.

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

To access the file you can use the path method: csv_file.path http://rdoc.info/gems/paperclip/Paperclip/Attachment#path-instance_method

This can be used along with for example the CSV reader.

@jon-m answer needs to be updated to reflect the latest changes to paperclip, in order for this to work needs to change to something like:

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

A bit convoluted as @jwadsack mentioned using Paperclip.io_adapters.for method accomplishes the same and seems like a better, cleaner way to do this IMHO.

You would need to load the contents of the file (using Rubys File.open) into a variable before you show it. This may be an expensive operation if your app gets lots of use, so it may be worthwhile reading the contents of the file and putting it into a text column in your database after uploading it.

Attachment already inherits from IOStream. http://rdoc.info/github/thoughtbot/paperclip/master/Paperclip/Attachment

So it should just be "#{attachment}" or <% RDiscount.new(attachment).to_html %> or send_data(attachment). However you wanted to display the data.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!