Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails + ActiveStorage on S3: Set filename on download?

Is there a way to change/set the filename on download?

Example: Jon Smith uploaded his headshot, and the filename is 4321431-small.jpg. On download, I'd like to rename the file to jon_smith__headshot.jpg.

View: <%= url_for user.headshot_file %>

This url_for downloads the file from Amazon S3, but with the original filename.

What are my options here?

like image 480
aaandre Avatar asked Feb 07 '18 20:02

aaandre


1 Answers

The built-in controller serves blobs with their stored filenames. You can implement a custom controller that serves them with a different filename:

class HeadshotsController < ApplicationController
  before_action :set_user

  def show
    redirect_to @user.headshot.service_url(filename: filename)
  end

  private
    def set_user
      @user = User.find(params[:user_id])
    end

    def filename
      ActiveStorage::Filename.new("#{user.name.parameterize(separator: "_")}__headshot#{user.headshot.filename.extension_with_delimiter}")
    end
end

Starting with 5.2.0 RC2, you won’t need to pass an ActiveStorage::Filename; you can pass a String filename instead.

like image 112
George Claghorn Avatar answered Sep 25 '22 11:09

George Claghorn