Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download and save a file using drakma:http-request and flexistreams

I am trying to download and save a PDF but it fails while writing with an EOF-Error. What would be the correct way of doing this?

(with-open-file (file "/home/*/test.pdf"
                      :direction :io
                      :if-does-not-exist :create
                      :if-exists :supersede
                      :element-type '(unsigned-byte 8))
  (let ((input (drakma:http-request "http://www.fractalconcept.com/ex.pdf"
                                    :want-stream t)))
    (awhile (read-byte input)
      (write-byte it file))
    (close input)))
like image 274
Sim Avatar asked Dec 27 '22 17:12

Sim


2 Answers

The solution was that I forgot to use the two optional parameters of read-byte.

The correct way would be to set eof-error-p and eof-value to nil:

(with-open-file (file "/home/*/test.pdf"
                      :direction :output
                      :if-does-not-exist :create
                      :if-exists :supersede
                      :element-type '(unsigned-byte 8))
  (let ((input (drakma:http-request "http://www.fractalconcept.com/ex.pdf"
                                    :want-stream t)))
    (awhile (read-byte input nil nil)
      (write-byte it file))
    (close input)))
like image 139
Sim Avatar answered Jan 13 '23 13:01

Sim


(ql:quickload "trivial-download")
(trivial-download:download URL FILE)

; Does pretty much exactly what your code does but in bigger chunks and can show a progress bar.

; QuickLisp can be found at http://QuickLisp.org.

like image 26
Devon Avatar answered Jan 13 '23 13:01

Devon