【问题标题】:no function clause matching in Plug.Conn.send_file/5Plug.Conn.send_file/5 中没有函数子句匹配
【发布时间】:2016-02-23 05:15:05
【问题描述】:

我正在尝试创建一个新路由,允许用户下载他们上传的文件。我在“/”范围内创建了这条路线。

get "/media/:filepath", MediaFilesController, :download

目前,我只是尝试发送位于项目根目录下的文件夹uploads 中的图像。简而言之,如果有人试图访问/media/file.png,它将发送位于<project_folder>/uploads/file.png 的文件。这是它的代码:

defmodule App.MediaFilesController do
  use App.Web, :controller
  import Plug.Conn

  @media_folder "/uploads"

  def download(conn, %{"filepath" => filepath}) do
    path = "#{System.cwd}/#{@media_folder}/#{filepath}"
    {:ok, file} = File.open(path)
    conn
    |> put_resp_content_type("image/png")
    |> send_file(200, file)
  end
end

当我尝试加载 URL /media/file.png 时,我收到此错误:

[error] #PID<0.579.0> running App.Endpoint terminated Server: localhost:4000 (http) Request: GET /media/file.png
** (exit) an exception was raised:
    ** (FunctionClauseError) no function clause matching in Plug.Conn.send_file/5

我不明白为什么会出现此错误。 documentation 准确地说:

使用Plug.Conn.send_file/5将其发回给客户。

为什么会出现这个错误?

【问题讨论】:

    标签: controller elixir phoenix-framework


    【解决方案1】:

    send_file/5 需要一个路径,而不是文件。

    所以最后这个函数是这样的:

    def download(conn, %{"filepath" => filepath}) do     
      path = "#{System.cwd}/#{@media_folder}/#{filepath}"
      conn                                               
      |> put_resp_content_type("image/png")              
      |> send_file(200, path)                            
    end                                                  
    

    【讨论】:

    • 要添加到这个答案,docs page 上的这个函数的类型是:“filename :: binary”。
    猜你喜欢
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 2023-03-13
    • 2017-11-30
    • 2015-03-20
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    相关资源
    最近更新 更多