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

Viewed 23489

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 contents of the uploaded file, but don't see contents as one of its attributes. What can I do here?

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 - Seems like all the Paperclip tutorials are about images, not text files.

7 Answers

This is a method I used for upload from paperclip to active storage and should provide some guidance on temporarily working with a file in memory. Note: This should only be used for relatively small files.

Written for gem paperclip 6.1.0

Where I have a simple model

class Post
  has_attached_file :image
end

Working with a temp file in ruby so we do not have to worry about closing the file

  Tempfile.create do |tmp_file|
    post.image.copy_to_local_file(nil, tmp_file.path)

    post.image_temp.attach(
      io: tmp_file,
      filename: post.image_file_name,
      content_type: post.image_content_type
    )
  end
Related