Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir - Download a File (Image) from a URL

Tags:

elixir

What does the code to download a file/image from a URL look like in Elixir?

Google searches seem to bring back how to download Elixir itself.

like image 249
BuddyJoe Avatar asked May 15 '15 20:05

BuddyJoe


1 Answers

Have a look at httpoison, an HTTP client for Elixir. You can just issue a GET request to the url pointing to the image (or file, it's irrelevant):

%HTTPoison.Response{body: body} = HTTPoison.get!("http://example.com/img.png") 

HTTPoison.get!/1 returns an HTTPoison.Response struct; I matched on that struct in order to get the body of the response. Now the body variables contains the image data (which is just a binary); you can write it to a file:

File.write!("/tmp/image.png", body) 

and there you go :).

This is obviously possible even without using httpoison, but you would have to deal with raw TCP connections (look at the gen_tcp Erlang module), parsing of the HTTP response and a bunch of stuff you usually don't want to do manually.

Whoops, forgot to mention the httpc Erlang module (included in the stdlib!), which makes this very simple without the need for a dependency like HTTPoison:

Application.ensure_all_started :inets  {:ok, resp} = :httpc.request(:get, {'http://example.com/my_image.jpg', []}, [], [body_format: :binary]) {{_, 200, 'OK'}, _headers, body} = resp  File.write!("/tmp/my_image.jpg", body) 
like image 128
whatyouhide Avatar answered Sep 18 '22 15:09

whatyouhide