使用Clojure将base64编码文件解码回原始格式

时间:2011-08-21 22:34:05

标签: clojure base64 mime-types

如何将已经base64编码的文件转换回原始格式并将其写入磁盘?例如,我有一个已经过mime64编码的pdf文件。该文件以:

开头
data:application/pdf;base64,JVBER

我想以正确的格式将其写入磁盘。我已经尝试了几个将字符串解码为字节数组的库(例如ring.util.codec),但如果我将生成的字节数组写入文件(使用spit),则文件显示已损坏。

更新:

PHP函数base64_decode似乎正在寻找我正在寻找的东西,因为它返回一个字符串。 Java中的等价物是什么?

2 个答案:

答案 0 :(得分:3)

在Clojure中,有data.codec(以前在clojure-contrib中)。

使用Java互操作性:

所以这些是我在使用data.codec时用于图像的辅助函数:

(require '[clojure.data.codec.base64 :as b64-codec])

(defn write-img! [id b64]
  (clojure.java.io/copy
   (decode-str (chop-header b64))
   (java.io.File. (str "/Users/nha/tmp/" id "." (b64-ext b64)))))

(defn decode-str [s]
  (b64-codec/decode (.getBytes s)))

(defn in?
  "true if the seq coll contains the element el"
  [coll el]
  (some #(= el %) coll))

(defn b64-ext [s]
  (if-let [ext (second (first (re-seq #"data:image/(.*);base64.*" s)))]
    (if (in? ["png" "jpeg"] ext)
      ext
      (throw (Exception. (str "Unsupported extension found for image " ext))))
    (throw (Exception. (str "No extension found for image " s)))))

(defn chop-header [s]
  (nth (first (re-seq #"(data:image/.*;base64,)(.*)" s)) 2))

答案 1 :(得分:2)

任何java库都应该可以运行(这里是来自Apache Commons的one,这里有一个完全来自Clojure-contrib的Clojure

我怀疑内容是以某种方式修改的,这意味着可以使用某种编码将字节转换为字符串,然后尝试使用不同的编码将此字符串读回字节。

第一步可能是检查服务器端文件中的字节数是否与您尝试读取的文件完全相同。 另外,尝试确认校验和(MD5)是否相同。

在任何情况下,PDF文件都是二进制文件,因此您不应将其转换为字符串,而应是直接字节。

相关问题