爲了具備通用性,將文件的內容讀到了fc變量中,fclen是fc的長度。fc也能夠是任何其它內容。curl 是 libcurl句柄。演示省略了不少顯而易見的步驟。app
1. 普通的post請求,這裏用curl_easy_escape對fc作了編碼curl
std::string data("req=plain");post
data.append("&file=");編碼
char *efc = curl_easy_escape(curl, fc, fclen);url
data.append(efc)code
curl_free(encoded);orm
curl_easy_setopt(curl, CURLOPT_URL, PURGE_URL);ip
curl_easy_setopt(curl, CURLOPT_POST, 1L);string
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());ast
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, data.size());
2. multipart/formdata請求
struct curl_httppost *formpost = 0;
struct curl_httppost *lastptr = 0;
curl_formadd(&formpost, &lastptr, CURLFORM_PTRNAME, "reqformat", CURLFORM_PTRCONTENTS, "plain", CURLFORM_END);
curl_formadd(&formpost, &lastptr, CURLFORM_PTRNAME, "file", CURLFORM_PTRCONTENTS, fc, CURLFORM_CONTENTSLENGTH, fclen, CURLFORM_END);
curl_easy_setopt(curl, CURLOPT_URL, URL);
curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
curl_easy_perform(curl);
curl_formfree(formpost);
3. multipart/formdata請求,不把文件讀入fc,其它步驟相同
curl_formadd(&formpost, &lastptr, CURLFORM_PTRNAME, "file", CURLFORM_FILE, "/path/filename", CURLFORM_END);
4. 經過put上傳文件
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
curl_easy_setopt(curl, CURLOPT_PUT, 1L);
curl_easy_setopt(curl, CURLOPT_READDATA, fp); // FILE *fp = fopen("/path/filename");
curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, fsize); // fsize = sizeof /path/filename
5. 發送本身的Header
struct curl_slist *slist = 0;
slist = curl_slist_append(slist, "Blog-X-User: username");
slist = curl_slist_append(slist, "Blog-X-Signature: signature");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist);
curl_slist_free_all(slist);