Created
November 9, 2021 09:09
-
-
Save bluzky/24c05615c58472e1a682d2cb704cd48a to your computer and use it in GitHub Desktop.
hash image file name arc uploader
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 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