Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

clojure - How to save the file in the server?

I'm receiving the following request in the server that I'm extracting using (-> req :params):

{"_parts":[["video",{"_data":{"size":2971246,"blobId":"D002459C-47C5-4403-ABC6-A2DE6A46230A","offset":0,"type":"video/quicktime","name":"DCDE604A-954F-4B49-A1F9-1BCC2C2F37BC.mov","__collector":null}}],["key","VAL"]]}

It contains a file "video" with a name and blobId. However, I want to access the file's data and save it to a file. So far, I've tried the following:

(defn upload-shot-video [req]
  (prn "uploading video")
  (prn "video is! " (-> req :multipart-params))
  (prn "video is " (-> req :params))
  (prn "video before is " (slurp (-> req :body)))
  (.reset (-> req :body))
  (prn "req full" (-> req))
  (prn "video after is " (-> req :body))
  (prn "video is! " (-> req :multipart-params))
  (clojure.java.io/copy (-> req :body) (clojure.java.io/file "./resources/public/video.mov"))

  (let [filename (str (rand-str 100) ".mov")]
    (s3/put-object
     :bucket-name "humboi-videos"
     :key filename
     :file "./resources/public/video.mov"
     :access-control-list {:grant-permission ["AllUsers" "Read"]})
    (db/add-video {:name (-> req :params :name)
                   :uri (str "https://humboi-videos.s3-us-west-1.amazonaws.com/" filename)}))
  (r/response {:res "okay!"}))

In which I'm trying to save the (-> req :body) into the file (which is an inputstream). This must be incorrect. What's the correct way to save this file that the server has received into a file, by saving the data into a file on the server? How to extract this data from the request?

question from:https://stackoverflow.com/questions/65879854/how-to-save-the-file-in-the-server

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you are using Ring, you need to use wrap-multipart-params middleware.

(ns controller
  (:require [ring.middleware.params :refer [wrap-params]]
            [ring.middleware.multipart-params :refer [wrap-multipart-params]])

(defn upload-shot-video [req]
  (let [uploaded-file (-> req :params "file" :tempfile) ;; here is a  java.io.File instance of your file
    (save-file uploaded-file)
    {:status 201 :body "Upload complete"}))

(def app
  (-> upload-shot-video
      wrap-params
      wrap-multipart-params))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...