Check out my book
on server deployment

Displaying, downloading and streaming files with Active Storage

Here is a quick’n’dirty cheat sheet for basic Active Storage actions.

Attaching

# in model
class Model
  has_one_attached :image
  has_many_attached :images # for more than one
end

# in controller
@model.image.attach(params[:image])
@model.image.attach(io: File.open("/path/to/file.jpg"), filename: "pic.jpg", content_type: "image/jpg")

Displaying

# in controller for including the attachment when querying
Model.all.with_attached_image
Model.all.with_attached_images

# in view
<%= image_tag @model.image %>
<%= @model.image.filename %>
<%= url_for(@model.image) %>

# variants
<%= image_tag @model.image.variant(resize: "500x500", monochrome: true) %>

Downloading

binary = @model.image.download

# or to create a file
include ActiveStorage::Downloading
tempfile = @model.image.download_blob_to_tempfile
# (needs a blob method to be defined)

There is also download_blob_to method that downloads the blog to a given file.

Streaming

# Stream from controller to show in browser (when supported)
response.headers["Content-Type"] = @model.image.content_type
response.headers["Content-Disposition"] = "inline; #{@model.image.filename.parameters}"

@model.image.download do |chunk|
  response.stream.write(chunk)
end

# Stream from controller to download
response.headers["Content-Type"] = @model.image.content_type
response.headers["Content-Disposition"] = "attachment; #{@model.image.filename.parameters}"

@model.image.download do |chunk|
  response.stream.write(chunk)
end

Join the Conversation

2 Comments

Leave a comment

Your email address will not be published. Required fields are marked *