Last active
October 10, 2016 12:26
-
-
Save radzserg/ca42b16420e7567f9fe4c52abaeff822 to your computer and use it in GitHub Desktop.
Upload manager for local storage - /lib/myapp/upload_manager/local.ex
This file contains 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 App.UploadManager.Local do | |
@behaviour App.UploadManager.Behavior | |
@config Application.get_env(:app, :file_manager)[:local] | |
@doc """ | |
Check if file exists | |
""" | |
def exists?(destination) do | |
destination = build_path(destination) | |
File.exists?(destination) | |
end | |
def save_from_file!(source, destination, _opts \\ %{}) do | |
destination = build_path(destination) | |
dirname = Path.dirname(destination) | |
case File.mkdir_p(dirname) do | |
:ok -> | |
File.copy!(source, destination) | |
:ok | |
{:error, reason} -> {:error, reason} | |
end | |
end | |
@doc """ | |
Save file to disk | |
""" | |
def save_from_content!(source, destination, _opts \\ %{}) do | |
destination = build_path(destination) | |
dirname = Path.dirname(destination) | |
case File.mkdir_p(dirname) do | |
:ok -> | |
File.write!(destination, source) | |
:ok | |
{:error, reason} -> {:error, reason} | |
end | |
end | |
@doc """ | |
Delete file from disk | |
""" | |
def delete!(destination) do | |
destination = build_path(destination) | |
File.rm(destination) | |
end | |
@doc """ | |
Save already existed in media storage file to local file | |
""" | |
def save_to_local_file!(source, destination) do | |
source = build_path(source) | |
File.copy(source, destination) | |
end | |
@doc """ | |
return URL for file | |
""" | |
def url(key) do | |
base_url = @config[:base_url] | |
"#{base_url}/#{key}" | |
end | |
# build full file path including base path from config | |
defp build_path(path) do | |
@config[:base_path] <> "/" <> path | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment