简体   繁体   中英

How to create a file resource on the fly in Clojure?

I have a database that contains images, and I want to serve these images through some urls, preferably like so:

foobar.com/items?id=whateverTheImageIdIsInTheDatabase. 

So I wrote this code:

(defn create-item-image []
(let [item-id (:id (:params req))
        item
        (find-by-id
         "items"
         (ObjectId. item-id)
         )
        file-location (str "resources/" item-id ".jpg")
        ]


    (with-open [o (io/output-stream  file-location)]
      (let [
            ;; take the first image. The "image" function simply returns the data-url from the id of the image stored in (first (:images item))
            img-string (get (str/split (image (first (:images item))) #",") 1)
            img-bytes
            (.decode (java.util.Base64/getDecoder) img-string)
            ]
        ;; write to a file with the name whateverTheImageIdIsInTheDatabase.jpg
        (.write o img-bytes)
        (.close o)
        )
      )

   )


)

(defn image-handler [req]
  (do
    (prn "coming to image handler")
    (create-item-image req)
    ;; send the resourc whateverTheImageIdIsInTheDatabase.jpg created above.
    (assoc (resource-response (str (:_id (:params req)) ".jpg") {:root ""})
           :headers {"Content-Type" "image/jpeg; charset=UTF-8"})
    )
  )

But this doesn't work. The resources are broken.Is it because the resource is sent before the file is created? How do I do send the resource on the fly? Another issue with writing a file on disk is that it has to stay there. So if 1000 requests for different images are made, all 1000 files would be stored in the server, which shouldn't be necessary since they are already in the database. Ultimately, how can I send these images stored as data-urls as files in the response without having to first write them to the disk?

Resources are static files which do not change over running the application and they are packed into uberjar when the server is compiled for production.

If you want to server an image in response, just convert it into byte array and send it within :body of response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM