Search code examples
ajaxclojureclojurescript

Http POST request with multipart/form-data using clj-ajax


I have an endpoint where I can upload a text file with curl like this:

curl -X POST -H "Content-Type: multipart/form-data" -F "file=@/resources/speciesDiffusion.tree" http://localhost:4000/continuous/tree 

now I need to send a similar request from a browser, but

 (ajax/ajax-request
  {:uri (str "http://localhost:4000" "/continuous/tree")
   :method :post
   :params {:treefile file}
   :handler #(println %1)
   :format (ajax/text-request-format)
   :response-format (ajax/json-response-format {:keywords? true})})

gives me a (nicely json converted, so I got that part going, which is nice) error response:

[false {:status 500, :status-text , :failure :error, :response {:timestamp 1494279686227, :status 500, :error Internal Server Error, :exception org.springframework.web.multipart.MultipartException, :message Current request is not a multipart request, :path /continuous/tree}}]

Also, in the browser I can see that the content-type headers is not correctly set, but I couldn't get it to work with any other combination of :format and :params.


Solution

  • There are some examples in the README of the cljs-ajax project. For example:

    (let [form-data (doto
                        (js/FormData.)
                      (.append "id" "10")
                      (.append "file" js-file-value "filename.txt"))]
      (POST "/send-file" {:body form-data
                          :response-format (raw-response-format)
                          :timeout 100}))
    

    https://github.com/JulianBirch/cljs-ajax