I have an operation that runs client side in the browser that creates a Uint8Array. I would like to somehow save this data from the browser to the database so that I can later load the data back into browser for other clients.
I’ve created a table with a :binary field, a schema and a changeset, but beyond that context I’m not sure what path to take to actually make the request from javascript land.
It’s a phoenix app. The page is not liveview but does have a channel connected. Either sending data thru http or websocket would be fine. I just don’t know how to send binary data when not using the eex form helpers. It’s the construction of the signed request that I think I’m lacking reference for
You can use form data like @evadne have suggested, or you can push the data through the phoenix channel. Phoenix channel supports binary data. With a liveview socket, you can’t send binary data directly but you can base64 encode into a string.
// data is Uint8Array
const blob = new Blob([data.buffer])
var fd = new FormData();
fd.append('space_id', "123")
fd.append('data', blob);
const up = () => {
fetch('/my_end_point/nav_mesh', {
method: 'POST',
headers: {
'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
'Content-Type': 'multipart/form-data',
"x-csrf-token": document.getElementsByName("csrf-token")[0]['content']
},
body: fd // This is your file object
}).then(
response => response.json() // if the response is a JSON object
).then(
success => console.log(success) // Handle the success response object
).catch(
error => console.log(error) // Handle the error response object
);
};
Controller:
def nav_mesh(conn, params) do
IO.inspect(params, label: "params")
conn |> json(%{})
end
When the js function executes I see the IO.inspect on the elixir logs, but get no “data” key in the params. Am I sending the binary data incorrectly? How do I get access to the binary data on the controller side?