Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send multiple files via HTTP POST with libcurl

I'm coding a C application which uploads a file using a simple HTTP POST request with libcurl. I am able to do it with one file, but I do not know how to upload multiple files. i tried using another method of the same code but to no avail. The code of the HTTP POST 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);
}
like image 219
user1758596 Avatar asked Oct 23 '12 07:10

user1758596


1 Answers

As illustrated by docs/examples/postit2.c sample code, and as stated by the doc [1], all you need to do is to 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);

/* ... */

Please note that I've used the CURLFORM_FILE option instead of CURLFORM_FILECONTENT that causes that file to be read and its contents used as data in this part. Make sure to use the proper option by checking the doc [1].

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

[1]

For CURLFORM_FILE the user may send one or more files in one part by providing multiple CURLFORM_FILE arguments each followed by the filename.

like image 137
deltheil Avatar answered Oct 04 '22 22:10

deltheil