Maybe with just the information above it is quite hard for people to help, here is a sample repository reproducing the same issue: GitHub - WannesFransen1994/phoenix-dynamic-images: serve dynamic images with phoenix · GitHub
once again some sample screenshots (same page reloaded twice):
relevant code:
controller -
def index(conn, _params) do
images = Repo.all(Image)
render(conn, "index.html", images: images)
end
def create(conn, %{"upload" => %Plug.Upload{} = up}) do
{:ok, _u} = up |> ImageContext.create_image()
redirect(conn, to: Routes.page_path(conn, :index))
end
def display(conn, %{"id" => id}) do
i = Repo.get(Image, id)
conn |> put_resp_content_type(i.content_type) |> send_file(200, Image.local_path(i))
end
imagecontext -
def create_image(%{filename: _, path: tmp_path, content_type: _} = upload) do
hash = File.stream!(tmp_path, [], 2048) |> Image.sha256()
with {:ok, %File.Stat{size: size}} <- File.stat(tmp_path),
data_merged <- Map.from_struct(upload) |> Map.merge(%{size: size, hash: hash}),
{:ok, upload_cs} <- %Image{} |> Image.changeset(data_merged) |> Repo.insert(),
:ok <- tmp_path |> File.cp(Image.local_path(upload_cs)) do
{:ok, upload_cs}
else
{:error, reason} -> Repo.rollback(reason)
end
end
Image -
schema "images" do
field :filename, :string
field :content_type, :string
field :hash, :string
field :size, :integer
end
def local_path(%Image{} = upload) do
[@upload_directory, "#{upload.id}-#{upload.filename}"] |> Path.join()
end




















