c - 使用 libcurl 通过 HTTP POST 发送多个文件

标签 c http-post libcurl

我正在编写一个 C 应用程序,该应用程序使用带有 libcurl 的简单 HTTP POST 请求上传文件。我可以用一个文件做到这一点,但我不知道如何上传多个文件。我尝试使用相同代码的另一种方法但无济于事。 HTTP POST 的代码如下:

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);
}

最佳答案

docs/examples/postit2.c 所示示例代码,如 the doc 所述[1],您需要做的就是为每个要上传的文件调用curl_formadd:

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);

/* ... */

请注意,我使用了 CURLFORM_FILE 选项而不是 CURLFORM_FILECONTENT ,这导致读取该文件并将其内容用作这部分的数据。确保通过检查文档 [1] 使用正确的选项。

专业提示:您可以使用 httpbin 等调试服务轻松测试您的代码或 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.

关于c - 使用 libcurl 通过 HTTP POST 发送多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13025479/

相关文章:

c - 在 C 中使用 libcurl 的单个 "init"从服务器检索数据

c - snprintf() c 中的段错误

c - 打印字符串指针导致 C 中的输出损坏

c - C中的错误输出

c - Windows 有可以从 C 调用的 JSON API 吗?

android - 多个 httpPost 到遥远的 Restful 服务 (JSON)

python - 如何使用发布数据重定向(Django)

javascript - Angularjs- 保留不存在的 dom 元素的数据 (ngIf=false)

c - libcurl 的内联证书而不是使用外部 bundle ?

IOS 获取代理设置