sparkle
sparkle

Reputation: 7398

Rails Active Storage upload to a public S3 remote url

I need to upload a video to a 3rd party via API. Using the API I have requested this "Upload Location" which is valid for 15-minute. Now I need to upload my Active Storage video directly to this remote upload location. This remote location is not managed by me.

I have read the official documentation but it's not clear where I can change the default upload location url with this one. Doc: https://edgeguides.rubyonrails.org/active_storage_overview.html#direct-uploads

Upload location:

 {"uploadLocation"=>"https://storage-3rd-party.s3.eu-west-1.amazonaws.com/staging/folderr/12345/xxxx?X-Amz-
Security-Token=xxx...."}

Upvotes: 1

Views: 1285

Answers (1)

Mark G.
Mark G.

Reputation: 3280

If I'm understanding correctly, you're going to want to implement a custom ActiveStorage::Service for this 3rd party API. Behind the scenes, rails invokes url_for_direct_upload to get the URL that you're wanting to customize.

You should be able to something close to working if you implemented a new service like so:

class ThirdPartyStorageService < ActiveStorage::Service

  def url_for_direct_upload(key, expires_in:, content_type:, content_length:, checksum:)
      ThirdPartyAPI.get_upload_location(...)
  end
  
  # Implement other abstract methods...
end

You then need to add your service in config/storage.yml:

third_party:
  service: ThirdPartyStorageService
  # username: ...
  # password: ...
  # other config...

And then you can set it up to be used in a specific model, or globally.

# app/models/my_model.rb
class MyModel
  has_one_attached :file, service: :third_party
end

# or config/application.rb
config.active_storage.service = :third_party

It's a bit of work, but I think this should set you up for success! Make sure to read the docs on ActiveStorage::Service and you can look at the implementations for Azure, AWS and Google storage services for inspiration if you aren't sure how to implement a certain method.

Upvotes: 1

Related Questions