r0man / cljs-http

A ClojureScript HTTP library.
582 stars 93 forks source link

Uploading files #22

Open xavi opened 10 years ago

xavi commented 10 years ago

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)})
myguidingstar-zz commented 10 years ago

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

xavi commented 10 years ago

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 .

robert-stuttaford commented 10 years ago

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

myguidingstar-zz commented 10 years ago

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

belo82 commented 9 years ago

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 commented 9 years ago

@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
ttasterisco commented 9 years ago

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