rails-activestorage - Rails 5.2 Rest API + Active Storage - 上传从外部服务接收的文件 blob

标签 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

最佳答案

在处理 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 .

关于rails-activestorage - Rails 5.2 Rest API + Active Storage - 上传从外部服务接收的文件 blob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51131723/

相关文章:

ruby-on-rails - 尝试附加带有 Active Storage 错误的文件

ruby-on-rails - 从 Active Storage 更改默认 url

ruby-on-rails - 没有要加载的文件——azure/storage.rb

ruby-on-rails - Rails 5 - 事件存储 - 变体 - 异常 : "#<MiniMagick::Error: ` mogrify -resize-to-fit [800, 800]"

ruby-on-rails - ActiveRecord::Migrator.up() 的 Rails 5.2 替代方案

javascript - 使用ajax更新表单后自动对焦不起作用

ruby-on-rails - 如何同步新的 ActiveStorage 镜像?

ruby-on-rails - Rails 7 - has_many_attached 加载新附件时删除旧附件

ruby-on-rails - 如何在 form_with 中设置作用域参数值

ruby-on-rails - 如何测试设置为稍后发送的电子邮件