ruby-on-rails - Upload a file from ActiveStorage to an API
问题描述
I'm trying to upload a file to an API with Httparty gem. Here is the requested format, from the documentation of this API:
Method: POST
Content-Type: application/json
{
"name": "filename.png",
"type": 2,
"buffer": "iVBOR..."
}
My document is stored with ActiveStorage, here is my function to download it and generate the parameters HASH:
def document_params
{
"name": @document.file.filename.to_s,
"type": IDENTIFIERS[@document.document_type],
"buffer": @document.file.download
}
end
Then I send the data with this function:
HTTParty.post(
url,
headers: request_headers,
body: document_params.to_json
)
The problem is that when I do document_params.to_json
, I get this error:
UndefinedConversionError ("\xC4" from ASCII-8BIT to UTF-8)
If I don't call to_json, data is not sent as a valid json, but as a hash representation like this: {:key=>"value"}
I would like to just send the file data as binary data, without trying to convert it to UTF-8.
解决方案
I found a solution: encoding the file content to Base64:
def document_params
{
"name": @document.file.filename.to_s,
"type": IDENTIFIERS[@document.document_type],
"buffer": Base64.encode64(@document.file.download)
}
end
推荐阅读
- html - Some CSS rules are not applied from external link
- javascript - justifiedGallery : 当屏幕 <800px 时尝试更改图像路径
- python - 如何使用 Python 在 Pycharm 调试模式下跳过行?
- jmeter - 删除 jmeter 中的 cookie
- databricks - 如何使用 API 将 Notebook 写入 Databricks?
- xamarin.forms - Xamarin Forms 版本 3.5.0.274416 中的 GetRenderer().NativeView 等效项
- python - 返回所有或特定列的频率计数的函数
- jquery - 我想在我的输入键功能上运行这个点击功能
- c - 带有 malloc 的 2d 数组声明 - 答案解释(参数)
- django - 评估 django-qr-code 生成的二维码中的转义序列