【问题标题】:Rails 5.2 Rest API + Active Storage - Upload file blob received from an external serviceRails 5.2 Rest API + Active Storage - 上传从外部服务接收的文件 blob
【发布时间】:2018-07-02 08:16:15
【问题描述】:

我们正在接收来自外部服务的 POST 调用,其中包含文件 blob(采用 Base64 编码)和一些其他参数。

# POST call to /document/:id/document_data
param = {
    file: <base64 encoded file blob>
}

我们希望处理文件并将其上传到以下模型

# MODELS
# document.rb  
class Document < ApplicationRecord
    has_one_attached :file
end

【问题讨论】:

    标签: rails-activestorage ruby-on-rails-5.2


    【解决方案1】:

    在处理 POST 调用的 Controller 方法中

    # 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
    

    希望这会有所帮助。

    更多关于 Tempfile 的信息可以在here找到。

    【讨论】:

    • 你在哪里看到它是“内存中的”?文档说:“[当]您需要一个太大而无法舒适地放入 RAM 的大字节缓冲区时,例如,当您正在编写 Web 服务器并且想要缓冲客户端的文件上传数据时”
    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 2020-02-01
    • 1970-01-01
    • 2021-10-08
    • 2018-09-28
    • 2022-11-28
    • 2022-11-11
    • 2023-03-13
    相关资源
    最近更新 更多