Upload file with HttpClient? [Solved]

Hello,

I am trying to upload a file to a server using HttpClient. I didn’t see any method on HttpClient or HttpRequest that seem to deal with files.

Is there a way to do it that I didn’t see, or must I implement it? There is a tutorial on libcurl http://curl.haxx.se/libcurl/c/libcurl-tutorial.html but HttpClient should be here to abstract that.

Here is the corresponding curl command-line (I can’t put the details though, it’s an authenticated API on a non-public site):

$ curl -H "Cookie: XXXX=XXX" http://servername/create_raw.json -F "files[]=@/path/to/file/image.png"

Thanks.

It just implements the http protocol. You have to study it, to know how post data is transferred. You are setting a content type, payload length, headers and the post data(the file itself). Those parameters and headers are abstracted by the HttpRequest. HttpClient then takes this request and sends it.

Post data is set with setRequestData:
http://www.cocos2d-x.org/reference/native-cpp/V3.3rc0/db/d8f/classcocos2d_1_1network_1_1_http_request.html#a711bdaeed5c51700acdb6318e66740cc

I know the http protocol, and HttpClient works just fine for the rest of my code (a lot of GET and POST, including some file download)

The issue, as I said, is that libcurl (which cocos2d::network uses under the hood) allows to “easily” send a file (instead of messing with the post data to re-implement correctly a file upload, which is reinventing the wheel in my books), while HttpClient/HttpRequest do not seem to have this feature.

As I said. You have to send files as post data. They do not have that feature. Files are just binary data and you have to deal with them as post data. So HttpClient/HttpRequest does deal with files :wink:

You are correct, that HttpClient/HttpRequest is using curl, but just for doing get/post requests. They are no complete curl wrappers. If you want to use the “easy send file curl feature”, you have to write a curl wrapper or use a third party lib.

HttpClient/HttpRequest was implemented for simple text stuff like utilizing RESTful APIs, not for binary data.

Update: I got it working. Here is a commit which modifies HttpClient and HttpRequest to be able to post a file: https://github.com/FenneX/FenneX/commit/134e9433c1dbc3ca6f772ce4c149bf911275a7e9

Some things may have to be changed to make it work, because the exact specifications may change depending on the server used. (in particular the content-type and copy name)