Add uploader.ex
This commit is contained in:
parent
1e36317c47
commit
ab12fb47a8
1 changed files with 25 additions and 0 deletions
25
lib/nulla/uploader.ex
Normal file
25
lib/nulla/uploader.ex
Normal file
|
@ -0,0 +1,25 @@
|
||||||
|
defmodule Nulla.Uploader do
|
||||||
|
def upload(%Plug.Upload{path: temp_path, filename: original_name}) do
|
||||||
|
{:ok, binary} = File.read(temp_path)
|
||||||
|
hash = :crypto.hash(:sha1, binary) |> Base.encode16(case: :lower)
|
||||||
|
file_type = Path.extname(original_name)
|
||||||
|
|
||||||
|
segments =
|
||||||
|
hash
|
||||||
|
|> String.slice(0, 15)
|
||||||
|
|> String.codepoints()
|
||||||
|
|> Enum.chunk_every(3)
|
||||||
|
|> Enum.map(&Enum.join/1)
|
||||||
|
|
||||||
|
filename = String.slice(hash, 15..-1) <> file_type
|
||||||
|
relative_path = Path.join(segments) <> "/" <> filename
|
||||||
|
|
||||||
|
dest_path = Path.join(["priv/static/files", relative_path])
|
||||||
|
|
||||||
|
dest_path |> Path.dirname() |> File.mkdir_p!()
|
||||||
|
|
||||||
|
File.write!(dest_path, binary)
|
||||||
|
|
||||||
|
relative_path
|
||||||
|
end
|
||||||
|
end
|
Loading…
Add table
Add a link
Reference in a new issue