【问题标题】:how can I serve static files from a non-default path?如何从非默认路径提供静态文件?
【发布时间】:2024-08-10 08:25:02
【问题描述】:

我正在使用 Plug.Static 从我的服务器提供静态文件。这样做的“默认”方式是像这样配置它:

  plug Plug.Static,
    at: "/my_project/assets",
    from: :my_project,
    gzip: true

然后我可以在 html 中使用 priv/static 中的文件,例如:

<img class='picture' src='<%= static_path(@conn, "/myPicture.png") %>'> 

到目前为止一切顺利。但是,如果我想在不同的路径提供来自 priv/static 的文件,我使用

  plug Plug.Static,
    at: "/my_project/another_path/assets",
    from: :my_project,
    gzip: true

现在我无法使用 static_path 访问文件,因为它仍然解析为 host.com/assets/my-picture-hash 而不是 host.com/another_path/assets/my-picture-hash,这是预期的行为。

当散列文件未在默认路径中公开时,如何获取其实际路径?

【问题讨论】:

    标签: phoenix-framework elixir


    【解决方案1】:

    您确定您的第一个示例有效吗?我认为该配置仅在称为 static_path(@conn, "/my_project/assets/myPicture.png) 时才有效。

    所以你的第二个例子在被称为static_path(@conn, "/my_project/another_path/assets/myPicture.png")时有效

    看起来您可能混淆了:at:to 选项。这是来自Plug.Static docs

    :at - 获取静态资源的请求路径。它必须是一个 字符串。

    :from - 从中​​读取静态资产的文件系统路径。有可能 要么:一个包含文件系统路径的字符串,一个原子表示 应用程序名称(资产将从priv/static 提供), 或包含应用程序名称和要服务的目录的元组 资产来自(除了priv/static)。

    所以要回答您问题的标题如何从非默认路径提供静态文件?);如果您想从不同的路径提供文件,而不是应用程序文件夹中的默认 priv/static,不应该是:

    plug Plug.Static, at: "/uploads", from: "/some/other/path"
    

    并显示位于您磁盘上/some/other/path/myPicture.png 的图像(这是一个绝对路径,与您的应用程序无关):

    <img class="picture" src="<%= static_path(@conn, "/uploads/myPicture.png") %>"> 
    

    (如果这仍然不起作用并且您已将其添加为新的Plug.Static默认值之后:将其放在之前默认静态插件。)

    编辑:

    当然,如果您想从默认路径(应用文件夹中的priv/static)提供静态资产但使用自定义 url,您可以这样做:

    plug Plug.Static, at: "/some/path", from: :my_project
    

    并将它们作为:

    <img class="picture" src="<%= static_path(@conn, "/some/path/myPicture.png") %>">
    

    【讨论】: