Yes.
当 ActiveStorage 由模型支持时,涉及两个部分:
- An
ActiveStorage::Blob
保存文件信息的记录active_storage_blobs
table
- An
ActiveStorage::Attachment
使用以下命令将 blob 连接到模型的记录active_storage_attachments
table
您可以跳过创建ActiveStorage::Attachment
如果您打电话,请录音create_and_upload! https://github.com/rails/rails/blob/6-1-stable/activestorage/app/models/active_storage/blob.rb#L112直接地。这将创建一个唯一的密钥,确定内容类型,计算校验和,将条目存储在active_storage_blobs
,并上传文件:
filename = 'local_file.txt'
file = File.open(filename)
blob = ActiveStorage::Blob.create_and_upload!(io: file, filename: filename)
您可以稍后下载:
blob.download
并删除:
blob.purge
如果您想跳过存储ActiveStorage::Blob
总的来说,您需要直接访问管理上传和下载文件的存储服务。例如,如果您正在使用Disk
存储你会看到这样的东西:
ActiveStorage::Blob.service
=> #<ActiveStorage::Service::DiskService ...
然后你必须生成自己的密钥并执行以下操作:
service = ActiveStorage::Blob.service
key = 'some_unique_key'
service.upload(key, file)
service.download(key)
service.delete(key)
要上传没有模型的文件,您可以use form_with并指定一个url https://guides.rubyonrails.org/form_helpers.html#uploading-files like:
<%= form_with url: "/uploads", multipart: true do |form| %>
<%= form.file_field :picture %>
<%= form.submit %>
<% end %>
然后在服务器上就可以得到file
with:
file = params[:picture]
blob = ActiveStorage::Blob.create_and_upload!(io: file, filename: file.original_filename)
...