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

后端 未结 6 1740
误落风尘
误落风尘 2020-12-05 07:24

I\'m using Paperclip / S3 for file uploading. I upload text-like files (not .txt, but they are essentially a .txt). In a show controller, I want to be able to get the cont

相关标签:
6条回答
  • 2020-12-05 07:26

    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.

    0 讨论(0)
  • 2020-12-05 07:28

    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
    
    0 讨论(0)
  • 2020-12-05 07:30

    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.

    0 讨论(0)
  • 2020-12-05 07:31

    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.

    0 讨论(0)
  • 2020-12-05 07:33

    @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.

    0 讨论(0)
  • 2020-12-05 07:35

    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.

    0 讨论(0)
提交回复
热议问题