Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use libcurl POST data and upload files

Shulou Source: shulou.com Published: 2022-06-02 07:47:47 10月03日 Update

This article focuses on "how to use libcurl POST data and upload files", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to use libcurl POST data and upload files.

For generality, the contents of the file are read into the fc variable, where fclen is the length of the fc. Fc can also be anything else. Curl is the libcurl handle. The demo omits many obvious steps.

1. Ordinary post request. Here fc is encoded with curl_easy_escape.

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 request

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 request. Do not read the file into fc. Other steps are the same.

Curl_formadd & formpost, & lastptr, CURLFORM_PTRNAME, "file", CURLFORM_FILE, "/ path/filename", CURLFORM_END)

4. Upload files via 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. Send your own 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)

At this point, I believe you have a deeper understanding of "how to use libcurl POST data and upload files". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Files content data steps learning practical common deeper same obvious interests variables handles practicality practical simple operation methods more friends coding Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Docker Linux Shulou Technology MariaDB