How to include file extension with LiveView Uploads?

Welcome @spyq!

You can’t trust what the client sends, but the File metadata provided by the browser is available on the UploadEntry.

You can use Path.extname/1 on the client name:

extname = Path.extname(entry.client_name)

…or if the client name has no extension, then you can try to derive it from the content type with MIME.extensions/1

  [extname] = MIME.extensions(entry.client_type)

…and if you have restricted allowed upload types with the :accept option on allow_upload/3 then it should always return an expected value.

…but none of that guarantees that the metadata is valid. If you need to know that those bytes are a JPEG you’ll need to use something like GenMagic which invokes libmagic under the hood and introspects the actual file bytes, and then invoke MIME.extensions/1 with the result mime_type to search for a known extension.

Hope that helps!

4 Likes