Rails 5.2 Rest API + Active Storage-上传从外部服务收到的文件Blob

时间:2018-07-02 08:16:15

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

我们正在从外部服务接收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

我们希望上传blob,而不写入磁盘上的实际文件,然后再上传。

1 个答案:

答案 0 :(得分:4)

在处理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)        # This creates an in-memory file 
  @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