rct*_*eil 12 ruby-on-rails rails-activestorage
Rails Active Storage 可以在没有模型支持的情况下使用吗?我有一个表格,需要上传文件,但我不希望将其附加到模型中。我只需要上传文件,以便我可以使用后台作业处理它,然后将其删除。
csc*_*oed 32
是的。
当 ActiveStorage 由模型支持时,涉及两个部分:
ActiveStorage::Blob中保存文件信息的记录active_storage_blobsActiveStorage::Attachment将 blob 连接到模型的记录active_storage_attachmentsActiveStorage::Attachment如果直接调用,可以跳过创建记录create_and_upload!。这将创建一个唯一的密钥,确定内容类型,计算校验和,在 中存储条目active_storage_blobs,然后上传文件:
filename = 'local_file.txt'
file = File.open(filename)
blob = ActiveStorage::Blob.create_and_upload!(io: file, filename: filename)
Run Code Online (Sandbox Code Playgroud)
您可以稍后下载:
blob.download
Run Code Online (Sandbox Code Playgroud)
并删除:
blob.purge
Run Code Online (Sandbox Code Playgroud)
如果您想完全跳过存储ActiveStorage::Blob,则需要直接转到管理上传和下载文件的存储服务。例如,如果您正在使用Disk存储,您会看到如下内容:
ActiveStorage::Blob.service
=> #<ActiveStorage::Service::DiskService ...
Run Code Online (Sandbox Code Playgroud)
然后你必须生成自己的密钥并执行以下操作:
service = ActiveStorage::Blob.service
key = 'some_unique_key'
service.upload(key, file)
service.download(key)
service.delete(key)
Run Code Online (Sandbox Code Playgroud)
要上传没有模型的文件,您可以使用form_with并指定url类似的内容:
<%= form_with url: "/uploads", multipart: true do |form| %>
<%= form.file_field :picture %>
<%= form.submit %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
然后在服务器上你可以得到file:
file = params[:picture]
blob = ActiveStorage::Blob.create_and_upload!(io: file, filename: file.original_filename)
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3773 次 |
| 最近记录: |