Send multiple files via HTTP POST using libcurl

I am encoding a C application that downloads a file using a simple HTTP POST request with libcurl. I can do this with one file, but I do not know how to upload multiple files. I tried using a different method of the same code, but to no avail. The HTTP POST code is as follows:

void sendHashes() { struct curl_httppost *post = NULL; struct curl_httppost *last = NULL; CURL *curlhash; CURLcode response; curlhash = curl_easy_init(); curl_easy_setopt(curlhash, CURLOPT_URL, URL); curl_formadd(&post, &last, CURLFORM_COPYNAME, "Hash", CURLFORM_FILECONTENT, "C:\\file.txt", CURLFORM_END ); curl_easy_setopt(curlhash, CURLOPT_HTTPPOST, post); response = curl_easy_perform(curlhash); curl_formfree(post); curl_easy_cleanup(curlhash); } 
+4
source share
1 answer

As docs/examples/postit2.c sample code, as document [1] indicated, all you need to do is call curl_formadd for each file you want to upload:

 curl_formadd(&post, &last, CURLFORM_COPYNAME, "Foo", CURLFORM_FILE, "foo.txt", CURLFORM_END); curl_formadd(&post, &last, CURLFORM_COPYNAME, "Bar", CURLFORM_FILE, "bar.txt", CURLFORM_END); /* ... */ 

Note that I used the CURLFORM_FILE parameter instead of CURLFORM_FILECONTENT , which forces this file to be read, and its contents are used as data in this part. Be sure to use the appropriate option by checking the document [1].

Pro-tip: you can easily test your code with a debugging service like httpbin or echohttp .

[1]

For CURLFORM_FILE, the user can send one or more files in one piece by supplying several CURLFORM_FILE arguments followed by the file name.

+4
source

Source: https://habr.com/ru/post/1441476/


All Articles