Skip to content

Instantly share code, notes, and snippets.

@bluzky
Created November 9, 2021 09:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bluzky/24c05615c58472e1a682d2cb704cd48a to your computer and use it in GitHub Desktop.
Save bluzky/24c05615c58472e1a682d2cb704cd48a to your computer and use it in GitHub Desktop.
hash image file name arc uploader
defmodule HeraCore.Uploader.AttachmentImage do
use Arc.Definition.Versioning
use Arc.Definition.Storage
# use Arc.Actions.Store
use Arc.Actions.Delete
use Arc.Actions.Url
use Arc.Ecto.Definition
# @versions [:original]
# @cwd File.cwd!()
# function override to store images locally.
def __storage do
Application.get_env(:arc, :storage)
end
# Whitelist file extensions:
def validate({file, _}) do
file_extension = file.file_name |> Path.extname() |> String.downcase()
~w(.jpg .jpeg .gif .png) |> Enum.member?(file_extension)
end
def storage_dir(_version, _) do
"images/attachments"
end
# Provide a default URL if there hasn't been a file uploaded
# def default_url(version, scope) do
# "/images/avatars/default_#{version}.png"
# end
def s3_object_headers(_version, {file, _scope}) do
# for "image.png", would produce: "image/png"
[content_type: MIME.from_path(file.file_name)]
end
def store(args) do
args = fix_filename(args)
Arc.Actions.Store.store(__MODULE__, args)
end
defp fix_filename(%{filename: filename} = file) do
file_name =
filename
|> Path.basename(Path.extname(filename))
|> Slugger.slugify_downcase()
file_name = "#{file_name}-#{Nanoid.generate(4)}#{Path.extname(filename)}"
%{file | filename: file_name}
end
defp fix_filename({file, scope}) do
{fix_filename(file), scope}
end
defp fix_filename(args), do: args
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment