cURL / Mailing Lists / curl-library / Single Mail

curl-library

How to upload file as CouchDB attachment via libCurl

From: Lane <software.research.development_at_gmail.com>
Date: Mon, 26 May 2014 15:49:16 -0500

I have been able to input a file using curl from the command line into
CouchDB, but I’m having an issue adding an attachment to CouchDB using
libcurl. This command line successfully does what I want. This is what I am
trying to duplicate via libcurl.

curl -X POST 'http://localhost:5984/students' -H 'Content-Type:
application/json' -d '{

    "first":"John", "last":"Doe", "age":"20", "_attachments": {

        "john.txt": {

            "content-type": "text/plain",

            "data": "'$(openssl base64 < /tmp/john_file.txt)'"

        }

    }

}'

And here is my attempt at trying to add an attachment to a document via
libcurl.

---
size_t json_callback(void *contents, size_t size, size_t nmemb, void *userp)
{
    ((string *)userp)->append((char *) contents, size * nmemb);
    return (size * nmemb);
}
ostringstream urlobj;
ostringstream lcobj;
// build json stream here …
// lcobj << ""{\"first\" : \"John"\"," << ...
string lcstr = lcobj.str();
string urlstr = urlobj.str();
hlist = NULL;
hlist = curl_slist_append(hlist,"Expect: 100-continue");
hlist = curl_slist_append(hlist,"Content-Type: application/json");
hlist = curl_slist_append(hlist,"charsets: utf-8");
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_URL, urlstr.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, hlist);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, lcstr.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, lcstr.length());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, json_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &rbuff);
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
    // ...
}
curl_easy_cleanup(curl);
curl_slist_free_all(hlist);
The above works for adding the following document (but not the attachment).
The stream lcobj contains the following document (minus carriage returns
for clarity here).
{ "first" : "John", "last" : "Doe", "age" : "20",
     "_attachments" : {"john_file.txt": {
            "content-type": "text/plain", "data": “how to put file here?”}
} }
The problem is I can’t seem to add a file as an attachment via libcurl (I
have no issues from the command line), but I’m not sure how the add the
file programmatically in the data field of _attachments here.

-------------------------------------------------------------------
List admin: http://cool.haxx.se/list/listinfo/curl-library
Etiquette: http://curl.haxx.se/mail/etiquette.html
Received on 2014-05-26