Image upload Json Api in elixir and phoenix

Sis Ccr
2 min readDec 4, 2020

--

Image upload with elixir and phoenix

Image upload in Elixir Phoenix with arc and arc_ecto

start by adding two dependencies

{:arc, “~> 0.11.0”},{:arc_ecto, “~> 0.11.3”}

I generated a context with

mix phx.gen.context Images Image images image

This is equivalent to

mix phx.gen.context ContextName Model tablename filename

This will generate a schema for images with a fieldname image of type string

Run arc generator

mix arc.g image_uploader

this will generate uploader file named image_uploader.ex in

lib >myapp_web>uploader> image_uploader.ex

add following in image_uploader.ex in order to use local (Ecto) as storage.

def __storage, do: Arc.Storage.Local

we can validate the type of file with

def validate({file, _}) do~w(.jpg .jpeg .gif .png) |> Enum.member?(Path.extname(file.file_name))end

here is the content for image_uplaoder.ex

Lets go back to schema for images, change the field images from string to

field :image, App.ImageUploader.Type

in config.exs we need to configure the setting for the storage directory. Here I configured storage directory as uploads in the root directory.

uploads directory is a root directory

Lets save our images from image_controller.ex

Images.create_image(image_params) is a simple function generated by the generator itself. no change needed for me in that.

Lastly write a ImageView to render the json and sent the image url.

At this point we can upload image and get the response back to postman.

but can we access that image with returned url? Nope, We will find error for now. One Last Tweak needed for this to work.

we need to specify which path we are serving the files in endpoint.ex. In my case its upload directory.

add this line to endpoint.ex

plug Plug.Static, at: "/uploads", from: Path.expand("./uploads"), gzip: false

Now we can access the image.

--

--

Sis Ccr
Sis Ccr

Written by Sis Ccr

Depths of ocean could not swallow me.

No responses yet