stavro / arc_ecto

An integration with Arc and Ecto.
255 stars 149 forks source link

Examples for saving arc photo from websocket? #107

Open quantumproducer opened 5 years ago

quantumproducer commented 5 years ago

How would you save a photo, will

  def update_photo(conn, %{"filename" => filename, "binary" => binary}) do
    %{filename: filename, binary: binary}
    |> ProfilePhoto.store()

work for websockets?

bnenu commented 5 years ago

Not so much to my knowledge, here is a similar issue opened #54 and there is an outstanding PR #87. It works with Plug.Upload%{} though so you can convert it before storing. There is an workaround in the issue and based on that here is how I handle it:

I am getting a base 64 encoded string in a JSON from the front-end, and processing like this:

  def process_image(base64encoded, name) do

    [media_type, input] = String.split(base64encoded, ";base64,", parts: 2)
    [_, ext] = String.split(media_type, "/", parts: 2)
    [_, content_type] = String.split(media_type, ":", parts: 2)

    filepath = Application.app_dir(:assets, "priv/uploads/#{name}.#{ext}")

    case File.write!("#{filepath}", Base.decode64!(input), [:binary]) do
      :ok ->
        %Plug.Upload{
          content_type: content_type,
          filename: "#{name}.#{ext}",
          path: Path.expand("#{filepath}") |> Path.absname()
        }

      {:error, reason} ->
        {:error, reason}
    end