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