cljs-http icon indicating copy to clipboard operation
cljs-http copied to clipboard

Uploading files

Open xavi opened this issue 11 years ago • 7 comments

Are there any plans to add support for file uploading?

Maybe could be supported using FormData and with an API like

(http/post "http://example.com" {:form-data-params (js/FormData. some-form-element)})

xavi avatar Sep 14 '14 08:09 xavi

I came to this need today and this is how I did it. cljs-http use XhrIo which accept FormData as request's body.

(defn generate-form-data [params]
  (let [form-data (js/FormData.)]
    (doseq [[k v] params]
      (.append form-data (name k) v))
    form-data))

(defn upload [file]
  (go (let [response (<! (http/post "http://localhost/upload"
                                    {:body (generate-form-data {:file file})}))]
        (prn (:status response))
        (prn (:body response)))))

;; some-dom-element is a single file upload input
;; <input type="file">
(upload (-> some-dom-element .-files first))

Btw, I can't write unit test for this because js/FormData only has .append method so there's no way to check what values it is holding

Do you want to support this, @r0man ? I'll make a PR then

myguidingstar-zz avatar Sep 15 '14 16:09 myguidingstar-zz

Ah, so it's already possible to upload files using cljs-http, it's just a matter of putting the FormData object in the :body. Thanks @myguidingstar .

xavi avatar Sep 16 '14 18:09 xavi

@myguidingstar perhaps it's worth just PR'ing a new section in the readme, so that it's easy for new folks to find?

robert-stuttaford avatar Oct 08 '14 13:10 robert-stuttaford

I think this should be included in API, as Ring has a middleware for that. Just made an PR https://github.com/r0man/cljs-http/pull/37

myguidingstar-zz avatar Nov 12 '14 05:11 myguidingstar-zz

Hi guys,

I'm trying to send multipart data to server, but I'm getting back the following error:

org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

I use Ring and wrap-multipart-params middleware on the server side. Problem is that client is not setting boundary as part of the Content-Type header.

My code to send data to server looks like this:

(client/request {:method :post :url "url" :multipart-params {:ke1 "value1" :ke2 "value2"}})

Have you guys any idea how to could I fix this problem?

belo82 avatar Mar 17 '15 14:03 belo82

@r0man can you please have a look at this pull request https://github.com/r0man/cljs-http/pull/51?

I removed explicit setting of content-type for multipart body so browser can set it to correct value. Something like

Content-Type: multipart/form-data;boundary=------FormBoundary14c28f17597

belo82 avatar Mar 17 '15 18:03 belo82

@r0man also close this one since PRs have fixed it? :p

ttasterisco avatar Jul 06 '15 09:07 ttasterisco