Reputation: 213
How would you download an image from a website and save it to the package folder in Common Lisp? I am having difficulty looking for such function in dexador's documentation.
Thanks in advance
Upvotes: 2
Views: 393
Reputation: 22776
This is slightly improved first version from Svante's answer:
(alexandria:write-byte-vector-into-file (dex:get "https://httpbin.org/image/png")
#P"/tmp/myfile"
:if-exists :supersede)
And this is slightly simplified version of his second version:
(serapeum:write-stream-into-file (dex:get "https://httpbin.org/image/png"
:want-stream t)
#P"/tmp/myfile"
:if-exists :supersede)
Alexandria and Serapeum both are collections of little helpers to simplify such tasks.
Upvotes: 0
Reputation: 51501
You get a byte vector back, so just save it:
(let ((bytes (dex:get uri)))
(with-open-file (out filename
:direction :output
:if-exists :supersede
:if-does-not-exist :create
:element-type 'unsigned-byte)
(write-sequence bytes out)))
If you have too much data, you might want to use a buffered stream copy:
(let ((byte-stream (dex:get uri :want-stream t))
(buffer (make-array buffer-size :element-type 'unsigned-byte)))
(with-open-file (out filename
:direction :output
:if-exists :supersede
:if-does-not-exist :create
:element-type 'unsigned-byte)
(loop :for p := (read-sequence buffer byte-stream)
:while (plusp p)
:do (write-sequence buffer out :end p))))
Upvotes: 6