Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions lib/waffle_ecto/schema.ex
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,18 @@ defmodule Waffle.Ecto.Schema do
when is_binary(filename) and is_binary(binary) ->
[{field, {upload, scope}} | fields]

{field, data = "data:image/" <> _}, fields ->
encoded_image = String.replace(data, ~r/^data\:image\/.*;base64,/, "")

case Base.decode64(encoded_image) do
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I looking for something similar and maybe it's worth to have special key like Arc
something like that %{filename: filename, base64: base64}

stolen from https://github.com/stavro/arc/pull/108/files

{:ok, binary_image} ->
upload = %{filename: unique_file_name(data), binary: binary_image}
[{field, {upload, scope}} | fields]

_ ->
fields
end

# If casting a binary (path), ensure we've explicitly allowed paths
{field, path}, fields when is_binary(path) ->
path = String.trim(path)
Expand All @@ -124,6 +136,11 @@ defmodule Waffle.Ecto.Schema do
end)
end

defp unique_file_name("data:image/" <> rest) do
extension = String.replace(rest, ~r/;base64,.*/, "")
"#{Ecto.UUID.generate()}.#{extension}"
end

def convert_params_to_binary(params) do
Enum.reduce(params, nil, fn
{key, _value}, nil when is_binary(key) ->
Expand Down
12 changes: 12 additions & 0 deletions test/schema_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -175,4 +175,16 @@ defmodule WaffleTest.Ecto.Schema do
)
)
end

test_with_mock "casting base64-encoded data struct attachments", DummyDefinition,
store: fn {%{filename: _, binary: _}, %TestUser{}} ->
{:ok, "file.png"}
end do
cs = TestUser.changeset(%TestUser{}, %{
"avatar" => "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="
})

assert cs.valid?
assert %{avatar: %{file_name: "file.png", updated_at: _}} = cs.changes
end
end