ben*_*tek 5 ruby ruby-on-rails rails-activestorage ruby-on-rails-6
我在中定义了两项服务storage.yml
amazon:
service: S3
bucket: bucket1
region: eu-central-1
access_key_id: 321
secret_access_key: 321
unsafe_files:
service: S3
bucket: unsafe-files
region: eu-central-1
access_key_id: 123
secret_access_key: 123
Run Code Online (Sandbox Code Playgroud)
我对某些文件使用亚马逊服务,我想unsafe_files对其他文件使用该服务,以便我可以将其放入另一个s3存储桶中。
使用该服务的模型unsafe_files如下所示(非常简单):
class Customer < ActiveRecord::Base
belongs_to :customer_image
end
Run Code Online (Sandbox Code Playgroud)
class CustomerImage < Image
has_one_attached :file, service: Rails.configuration.settings[:unsafe_files_service]
end
Run Code Online (Sandbox Code Playgroud)
Rails.configuration.settings[:unsafe_files_service]只是unsafe_files
application.rb在我正在设置的轨道上
config.active_storage.service = :amazon因此默认情况下它使用amazon定义的服务storage.yml
现在我想使用 直接上传文件form_with,也很简单:
<%= form_with model: [@customer, CustomerImage.new] do |form| %>
<%=
form.file_field :file,
accept: 'image/jpeg',
direct_upload: true,
multipart: true
%>
<%= form.submit "submit" %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
现在我知道(或者我认为我知道)使用active_storage. 一些 JavaScript 监听表单提交事件,首先获取其中的内容file_field并将其发送到DirectUploadsController检查图像,生成直接上传 url,然后我们直接将文件上传到指定的服务。一切都在这里: https: //github.com/rails/rails/blob/6ecf1065da57360bdc9f1d85e2c2d9314dcb79e0/activestorage/app/controllers/active_storage/direct_uploads_controller.rb#L14
该服务使用文件密钥或 ID 进行响应。然后,表单提交继续,我们保存收到的 ID,这就是文件之间的关系。
但是,当我们点击DirectUploadsController并创建 blob 时,它会获得默认的 service_name (请参阅: https: //github.com/rails/rails/blob/6ecf1065da57360bdc9f1d85e2c2d9314dcb79e0/activestorage/app/models/active_storage/blob.rb#L115)
长话短说,当使用直接上传时,我无法选择服务,我必须依赖 Rails 默认服务。
有解决方法吗?或者也许我错过了什么?
如果您想调用create_before_direct_upload!自己(以便可以指定 service_name),那么我认为您必须以DirectUploadsController某种方式覆盖。您可以编写自己的控制器,或者(高级)尝试重新打开并修补DirectUploadsController. 我的应用程序执行前者。
来自OP的更新:
\n\n\n我最终重新打开 DirectUploadsController (并且还在表单 file_field 中添加了一个选项来传递自定义 direct_upload_url 它工作得很好,尽管我不喜欢我不得不与内部人员打交道。我检查了 active_storage gem ,看起来必须添加此功能,因为当前的实现没有解决方法。\xe2\x80\x93 beniutek
\n
| 归档时间: |
|
| 查看次数: |
1723 次 |
| 最近记录: |