Advertisement
vmeansdev

Chunked upload

Jul 8th, 2020
2,236
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (defn upload-chunked
  2.   [params]
  3.   (let [headers (:headers params)
  4.         content-range (rest (re-matches #"(\d+)-(\d+)\/(\d+)" (get headers "content-range")))
  5.         content-length  (parse-int (get headers "content-length"))
  6.         [start end total] (map parse-int content-range)
  7.         body-stream (:body params)
  8.         file-name (get headers "x-file-name" "")
  9.         hash (sha1-str (str file-name total))
  10.         dest-path (files/file-path (uploads-path) (files/make-new-name hash file-name))
  11.         file (io/file dest-path)
  12.         file-size (.length file)
  13.         stream (io/output-stream dest-path :append true)]
  14.     (if (= (+ 1 end) file-size)
  15.       (do
  16.         (dispose-stream stream)
  17.         (response/created (result/success)))
  18.       (if (not (= start file-size))
  19.         (do
  20.           (dispose-stream stream)
  21.           (io/delete-file dest-path true)
  22.           (response/bad-request (result/failure "start != file-size")))
  23.         (try
  24.           (io/copy body-stream stream)
  25.           (if (>= (+ start content-length) total)
  26.             (do
  27.               (dispose-stream stream)
  28.               (response/ok (result/success)))
  29.             (response/created))
  30.           (catch Exception e
  31.             (dispose-stream stream)
  32.             (response/bad-request (result/failure "Chunked upload has failed!"))))))))
Advertisement
RAW Paste Data Copied
Advertisement