clojure - 如何在 Clojure 中将二进制文件的内容读入字符串?

标签 clojure

我正在 Clojure 中使用 Compojure 创建静态文件服务器,但我一直坚持从文件系统读取图像并通过 Compojure 路由显示该图像。

不幸的是,slurp 不能很好地处理二进制数据,从那以后我尝试了 100 种不同的方法,但这是我最近的失败尝试:

(defn image-output [filepath]
  (try
    (let [contents (apply str (with-open [rdr (io/reader filepath)]
      (into #{} (line-seq rdr))))]
      {
        :status 200
        :headers 
        {
          "Content-Type" "image/jpeg", 
          "Content-Length" "",
          "Cache-Control" "",
          "Expires" ""
        }
        :body contents
      }))
    (catch Exception e {:status 404})))

(defn endpoint_view [params]
  (if (contains? params :bucket)
    (image-output (join "/" [data_path (:bucket params) (:dir params) (:filename params)]))))

(defroutes main-routes
  (GET "/view/:bucket/:dir/:filename" {params :params} (endpoint_view params))
  (route/files "/")
  (route/resources "/s" {:root "./public/s"})
  (route/not-found "Page not found"))

看来当前的尝试遇到了与使用 slurp 相同的命运,我可以回显内容字符串及其编码字符串,但是当我将内容类型更改为 image/jpeg 时,它是一个损坏的图像。

我昨天花了一整天的时间进行谷歌搜索,但是没有一个示例实现了相同的目标,虽然它们帮助我更多地了解了 Java IO,但它们还不够清晰,无法帮助我到达我需要去的地方,或产生与我已经得到的相同结果(例如: Best way to read contents of file into a set in Clojure )。

(如果您能告诉我如何从文件路径获取内容类型,那就是想象中的奖励分,这也是我的下一个问题!)

最佳答案

只需将正文设置为(io/file filepath) - Ring 非常乐意为您提供文件服务。

编辑以获得奖励积分:您可以使用ring.middleware.file-info/wrap-file-info来获取您返回的文件的文件元数据。或者,您可以使用 (compojure.route/files "/public") 提供整个目录,它会为您解决所有这些麻烦。

关于clojure - 如何在 Clojure 中将二进制文件的内容读入字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11368420/

相关文章:

Clojure 函数打印符号名称和符号值

java - 构建器模式和 DSL 是等效的——还是更具表现力?

clojure - 有没有一些方法可以避免 clojure 中出现这种重复代码?

Emacs 声称我引用了一个 lambda,但我不是

function - 将java方法名称作为clojure中的函数arg

clojure - 在 Clojure 中使用平面文件作为数据存储和引用作为表?

multithreading - Clojure 可变存储类型

clojure - 在 Clojure 中使用 WSDL

bash - 使用 bash 为 clojure 传递参数

java - 让 clojure 生成一个像构建器模式一样使用的 java 类