How do you POST
binary data? In my specific case, I want to send an image to Matrix/Synapse messenger.
I’m migrating from OpenHAB where used a workaround like this:
// OpenHAB natively can't send binary data but you can Base64 encode binary data
var Base64 = Java.type("java.util.Base64")
var result = actions.HTTP.sendHttpPostRequest(
"https://example.com/upload", "application/json",
JSON.stringify({
filename: "snapshot.jpg",
data: Base64.getEncoder().encodeToString(Java.to(imageData, "byte[]"))
}), 3000
);
First I tried rest_scripts
, but it cannot figure out how to send binary data either.
Second I tried python_scripts
. Either to send binary data directly, or to base64
encode the data. But I couldn’t figure this out as the python_scripts
don’t allow import
statements
# Doesn't work
import requests
with open(image_path, "rb") as f:
data = f.read()
request('POST',
f'https://example.com/upload?filename={filename}',
body=data,
headers=headers)
# Doesn't work
import base64
with open(image_path, "rb") as f:
data = f.read()
print(base64.b64encode(binary).decode())
exit(0)
Finally I tried shell_scripts
to run curl
:
shell_command:
matrix_snapshot: >
curl -X POST
-H "Content-Type: image/jpeg"
-H "Authorization: {{ bearer }}"
--data-binary "@{{ filename }}"
https://example.com/upload?filename=snapshot.jpg
This works, but it doesn’t feel right. It’s a hack using a long string escape disaster waiting to happen if I start expanding on this. Hoping curl
will remain available in the shell.
Are there prettier solutions available that I’m just missing? I still consider myself a novice in Home Assistant.