使用libcurl POST資料和上傳檔案

來源:互聯網
上載者:User

標籤:blog   http   ar   os   使用   sp   for   on   檔案   

  • 為了具有通用性,將檔案的內容讀到了fc變數中,fclen是fc的長度。fc也可以是任何其它內容。curl 是 libcurl控制代碼。示範省略了很多顯而易見的步驟。 1. 普通的post請求,這裡用curl_easy_escape對fc做了編碼std::string data("req=plain");data.append("&file=");char *efc = curl_easy_escape(curl, fc, fclen);data.append(efc)curl_free(encoded); curl_easy_setopt(curl, CURLOPT_URL, PURGE_URL);curl_easy_setopt(curl, CURLOPT_POST, 1L);curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());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. 發送自己的Headerstruct 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);

使用libcurl POST資料和上傳檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.