anu*_*rag 5 rails-activestorage ruby-on-rails-5.2
我们正在接收来自外部服务的 POST 调用,其中包含文件 blob(采用 Base64 编码)和一些其他参数。
# POST call to /document/:id/document_data
param = {
file: <base64 encoded file blob>
}
Run Code Online (Sandbox Code Playgroud)
我们想要处理文件并将其上传到以下模型
# MODELS
# document.rb
class Document < ApplicationRecord
has_one_attached :file
end
Run Code Online (Sandbox Code Playgroud)
在处理 POST 调用的控制器方法中
# documents_controller.rb - this method handles POST calls on /document/:id/document_data
def document_data
# Process the file, decode the base64 encoded file
@decoded_file = Base64.decode64(params["file"])
@filename = "document_data.pdf" # this will be used to create a tmpfile and also, while setting the filename to attachment
@tmp_file = Tempfile.new(@filename) # When a Tempfile object is garbage collected, or when the Ruby interpreter exits, its associated temporary file is automatically deleted.
@tmp_file.binmode # This helps writing the file in binary mode.
@tmp_file.write @decoded_file
@tmp_file.rewind()
# We create a new model instance
@document = Document.new
@document.file.attach(io: @tmp_file, filename: @filename) # attach the created in-memory file, using the filename defined above
@document.save
@tmp_file.unlink # deletes the temp file
end
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。
可以在此处找到有关 Tempfile 的更多信息。
| 归档时间: |
|
| 查看次数: |
2519 次 |
| 最近记录: |