Created
July 17, 2017 17:38
-
-
Save marysaka/1f5b404d9fe6b8ecabf04fe07399bfeb to your computer and use it in GitHub Desktop.
Simple Puush Uploader in Elixir (httpc/crypto deps)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Puush do | |
def up(key, file_name), do: up(key, file_name, File.read!(file_name)) | |
def up(key, name, data) do | |
boundary = "------#{:crypto.strong_rand_bytes(128) |> Base.encode16}" | |
payload = multipart_payload(boundary, [{"z", "waifu"}, {"k", key}], [{"f", name, data}]) | |
case :httpc.request(:post, {'https://puush.me/api/up', [], 'multipart/form-data; boundary=#{boundary}', payload}, [], []) do | |
{:ok, {{_,200,_},_,body}} -> | |
case body |> to_string |> String.split(",") do | |
["0", url,_,_] -> {:ok, url} | |
data -> {:error, List.first(data)} | |
end | |
_ -> {:error, nil} | |
end | |
end | |
def multipart_payload(boundary, fields, files) do | |
fieldsPart = Enum.map(fields, fn ({key, value}) -> | |
[ | |
"--#{boundary}", | |
"Content-Disposition: form-data; name=\"#{key}\"\r\n", | |
"#{value}" | |
] | |
end) |> List.flatten | |
filesPart = Enum.map(files, fn ({key, file_name, file_content}) -> | |
[ | |
"--#{boundary}", | |
"Content-Disposition: form-data; name=\"#{key}\"; filename=\"#{file_name}\"", | |
"Content-Type: application/octet-stream\r\n", | |
"#{file_content}" | |
] | |
end) |> List.flatten | |
(fieldsPart ++ filesPart ++ ["--#{boundary}--"])|> Enum.join("\r\n") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment