I’m surprised this question isn’t a little more common. I’m working with a frontend React programmer who is building our iPhone app. He is uploading images to my code (running on the server). He base64 encodes the image and that uploads it to my code. I then have the data in a map of items, and I loop over the items. Each profile can have 4 images. I try to decode the base64 images and then write them to disk.
I write the data to disk, but when I then try to look at the image through the web browser, it is broken. I get an icon suggesting it is broken.
So maybe I’m decoding things wrong? Or is spit converting the binary back to text?
Here is my code, I’m wondering which step I’m getting wrong?
At least for now, all of the test data I have the base64 encoded data starts with:
/9j/
So I assume it is all JPEG.
Actually I know it is JPEG because if I hardcode a data src for a img tag in HTML, it does render correctly, using the encoded base64.
But my attempts to decode and write to disk are failing somehow, the data is getting mangled.
(defn encode [to-encode]
(.encode (Base64/getEncoder) (.getBytes to-encode)))
(defn decode [to-decode]
(String. (.decode (Base64/getDecoder) to-decode)))
(defn item-image [item-id image]
(if (nil? image)
nil
(if (= (subs image 0 4) "http")
image
(if (= (subs image 0 4) "/9j/")
(do
(spit (str (System/getenv "path_to_images") item-id ".jpeg") (decode image))
(str "https://api.left-field.co/images/" item-id ".jpeg"))
(do
(spit (str (System/getenv "path_to_images") item-id ".png") (decode image))
(str "https://api.left-field.co/images/" item-id ".png"))))))
(defn item-images [item]
(when (map? item)
(let [
item (assoc item :image1 (item-image (:item-id item) (:image1 item)))
item (assoc item :image2 (item-image (:item-id item) (:image2 item)))
item (assoc item :image3 (item-image (:item-id item) (:image3 item)))
item (assoc item :image4 (item-image (:item-id item) (:image4 item)))
]
(update-items item))))
(defn item-images-all []
(try
(doseq [x (vals @items)]
(log/log "item-images-all")
(log/log x)
(item-images x))
(catch Exception e (log/log e))))