问题
Im using the phoenix framework to create a webpage and created an upload form to give the user the possiblity to upload a profil picture.
def update(conn, %{"id" => id, "user" => %{"photo" => file}}) do
if(File.exists?(file.path)) do
case File.read(file.path) do
{:ok, body} -> data = IO.iodata_to_binary(body)
changeset = Whiteboard.File.changeset(%Whiteboard.File{}, %{user_id: currentuser.id, name: file.filename , data: data})
so that works and the binary data is in the database as bytea/binary.
Now my question: How do I render the binary data in the phoenix html.eex file to show the image again?
edit: found one solution
def render("image.html", %{:height => height, :width => width, :data => data, :datatype => datatype}) do
pic = Base.encode64(data)
Phoenix.HTML.raw("<img src=\"data:image/"<>datatype<>";base64,"<>pic<>"\" height=\""<>height<>"\" width=\""<>width<>"\">")
end
回答1:
While browsers support adding base64 image URLs, I would suggest that you take the traditional approach that caches can use more easily, and create a new Phoenix route that serves up the image.
To do this, you simply need to emit the correct mime type header and instead of rendering a template you simply place the contents of the column into the connection directly.
You should probably inspect the first few bytes to see if it matches a whitelist of known formats. You can search for what these bytes are here: http://www.garykessler.net/library/file_sigs.html
来源:https://stackoverflow.com/questions/35386707/phoenix-elixir-binary-data-image