【问题标题】:Upload a file from ActiveStorage to an API将文件从 ActiveStorage 上传到 API
【发布时间】:2021-02-09 19:13:39
【问题描述】:

我正在尝试使用 Httparty gem 将文件上传到 API。 以下是此 API 文档中请求的格式:

Method: POST
Content-Type: application/json   
{
  "name": "filename.png",
  "type": 2,
  "buffer": "iVBOR..."
}

我的文档是用 ActiveStorage 存储的,这是我下载它并生成参数 HASH 的函数:

def document_params
  {
    "name": @document.file.filename.to_s,
    "type": IDENTIFIERS[@document.document_type],
    "buffer": @document.file.download
  }
end

然后我用这个函数发送数据:

HTTParty.post(
  url,
  headers: request_headers,
  body: document_params.to_json
)

问题是当我做document_params.to_json 时,我得到这个错误:

UndefinedConversionError ("\xC4" 从 ASCII-8BIT 到 UTF-8)

如果我不调用 to_json,则数据不会作为有效的 json 发送,而是以这样的哈希表示形式发送:{:key=>"value"}

我只想将文件数据作为二进制数据发送,而不是尝试将其转换为 UTF-8。

【问题讨论】:

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


    【解决方案1】:

    我找到了解决办法:将文件内容编码为Base64:

    def document_params
      {
        "name": @document.file.filename.to_s,
        "type": IDENTIFIERS[@document.document_type],
        "buffer": Base64.encode64(@document.file.download)
      }
    end
    

    【讨论】:

      猜你喜欢
      • 2018-10-10
      • 1970-01-01
      • 2019-07-23
      • 2021-04-12
      • 2012-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多