【问题标题】:Serving binary files from the database with compojure使用 compojure 从数据库中提供二进制文件
【发布时间】:2011-04-28 15:48:06
【问题描述】:

我有以下路线定义:

(require '[compojure.core :as ccore]
         '[ring.util.response :as response])

(def *main-routes*
     (ccore/defroutes avalanche-routes
       (ccore/GET "/" [] "Hello World 2")
       (ccore/GET "/images/:id" [id] (get-image-response id))))

在此示例中,请求 / 就像一个魅力,并返回预期的 Hello World 2

get-images-response 方法定义如下:

(defn get-image-response
  [id]
  (let [record (db/get-image id false)]
    (-> (response/response (:data record))
        (response/content-type (:content-type record))
        (response/header "Content-Length" (:size record)))))

我得到了一个 404,所以二进制文件的服务还不能很好地工作。任何想法为什么?

编辑: 好的,问题与在/images/name.jpg 上请求图像的事实有关。一旦我删除.jpg,处理程序就会被调用。所以问题就变成了我如何匹配除了扩展名之外的任何东西?

【问题讨论】:

    标签: clojure binary-data compojure


    【解决方案1】:

    在这种情况下,真正的答案是 clojure-couchdb 库中存在错误。补丁可用on github here

    归结为将 {:as :byte-array} 映射参数和值添加到通过 clj-http 发送到沙发 api 的请求中。

    我的代码中的另一个问题是ring 在渲染字节数组时并不真正知道如何处理它们。我没有修补环,而是将字节数组包装成java.io.ByteArrayInputStream。以下是处理下载的完整代码:

    (defn get-image-response
      [id]
      (let [record (db/get-image id false)]
        (-> (response/response (new java.io.ByteArrayInputStream (:data record)))
            (response/content-type (:content-type (:content-type record)))
            (response/header "Content-Length" (:size record)))))
    

    【讨论】:

      【解决方案2】:

      Compojure 使用clout 进行路由匹配。点字符在影响力路线中具有特殊含义。它表示一个标记分隔符,类似于斜杠字符。以下字符在影响力中都有这个含义:/ . , ; ?

      这意味着像"/images/:id" 这样的路由不会匹配/images/name.jpg 形式的uri,因为imagesnamejpg 在影响力中分别代表一个单独的标记。

      为了匹配它,您可以根据需要以多种不同的方式编写路线。

      如果您的所有图片都有.jpg 扩展名,那么最简单的做法是:

      (GET "/images/:id.jpg" [id] ...)
      

      如果扩展名不同,您可以执行以下操作:

      (GET "/images/:name.:extension" [name extension] ...)
      

      如果你想限制扩展,你可以通过 compojure/clout 一个正则表达式:

      (GET ["/images/:name.:ext", :ext #"(jpe?g|png|gif)"] [name ext] ...)
      

      你也可以使用通配符,它​​不太精确,可以匹配任何以/images/开头的uri:

      (GET "/images/*" [*] ...)
      

      【讨论】:

      • 感谢您提供的信息,我投票支持您,因为它是正确的并且与我的问题相关。不幸的是,我真正的问题是 clojure-couchdb 库中的一个错误,我已经对其进行了修补。我将在单独的答案中包含所有详细信息,以便其他人可以参考。
      猜你喜欢
      • 2016-06-20
      • 2012-02-11
      • 1970-01-01
      • 2014-05-11
      • 1970-01-01
      • 1970-01-01
      • 2011-04-08
      • 2016-01-10
      • 2013-05-25
      相关资源
      最近更新 更多