凤凰elixir二进制数据图像 [英] phoenix elixir binary data image

查看:198
本文介绍了凤凰elixir二进制数据图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用凤凰框架创建一个网页并创建一个上传表单,以便用户可以上传个人资料图片。

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})

因此工作和二进制数据在数据库中为bytea / binary。

so that works and the binary data is in the database as bytea/binary.

现在我的问题:如何在phoenix html.eex文件中渲染二进制数据以再次显示图像?

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


推荐答案

虽然浏览器支持添加base64图像网址,但我建议使用你采用传统的方法,缓存可以更容易地使用,并创建一个新的凤凰路线,提供图像。

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.

要做到这一点,你只需要发出正确的mime类型标题,而不是渲染模板,你只需将列的内容直接放入连接。

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.

你应该检查前几个字节,看它是否匹配已知格式的白名单。您可以在此搜索这些字节: http://www.garykessler.net/library/file_sigs .html

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

这篇关于凤凰elixir二进制数据图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆