如何将带有 -F 选项的 curl 命令转换为 libcurl

How to convert curl command with -F option to libcurl

我使用这样的 curl 命令成功将图像文件上传到我的博客。

curl -F 'access_token=xxx' -F 'blogName=xxx' -F 'uploadedfile=@xxx.png' https://www.tistory.com/apis/post/attach

并且...为了在我的 C++ 项目中使用它,我将它转换为 libcurl,就像这样。

curl = curl_easy_init();

if (curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "https://www.tistory.com/apis/post/attach");
    curl_easy_setopt(curl, CURLOPT_USERAGENT, "curl/7.61.0");

    curl_mime *formpost = curl_mime_init(curl);
    curl_mimepart *part = nullptr;

    part = curl_mime_addpart(formpost);
    curl_mime_name(part, "access_token");
    curl_mime_data(part, "xxx", CURL_ZERO_TERMINATED);

    part = curl_mime_addpart(formpost);
    curl_mime_name(part, "blogName");
    curl_mime_data(part, "xxx", CURL_ZERO_TERMINATED);

    part = curl_mime_addpart(formpost);
    curl_mime_name(part, "uploadedfile");
    curl_mime_filename(part, "xxx.png");
    curl_mime_type(part, "image/png");

    curl_easy_setopt(curl, CURLOPT_MIMEPOST, formpost);
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);

    res = curl_easy_perform(curl);

    ...
}

此转换后的代码无效。结果是响应代码400。实际上我不知道libcurl的什么功能对应于curl命令的-F选项。有人让我知道如何将顶部的这个 curl 命令转换为 libcurl,或者我必须研究什么功能。提前致谢。

在 运行 之后执行以下命令(这里有用!):

curl -F 'access_token=xxx' -F 'blogName=xxx' -F 'uploadedfile=@xxx.png' https://www.tistory.com/apis/post/attach --libcurl example.cc && cat example.cc

我得到了以下代码(为了便于阅读而整理了一下):

#include <curl/curl.h>

int main(int argc, char *argv[])
{
  CURLcode ret;
  CURL *hnd;
  curl_mime *mime1;
  curl_mimepart *part1;

  mime1 = NULL;

  hnd = curl_easy_init();
  curl_easy_setopt(hnd, CURLOPT_BUFFERSIZE, 102400L);
  curl_easy_setopt(hnd, CURLOPT_URL, "https://www.tistory.com/apis/post/attach");
  curl_easy_setopt(hnd, CURLOPT_NOPROGRESS, 1L);
  mime1 = curl_mime_init(hnd);
  part1 = curl_mime_addpart(mime1);
  curl_mime_data(part1, "xxx", CURL_ZERO_TERMINATED);
  curl_mime_name(part1, "access_token");
  part1 = curl_mime_addpart(mime1);
  curl_mime_data(part1, "xxx", CURL_ZERO_TERMINATED);
  curl_mime_name(part1, "blogName");
  part1 = curl_mime_addpart(mime1);
  curl_mime_filedata(part1, "xxx.png");
  curl_mime_name(part1, "uploadedfile");
  curl_easy_setopt(hnd, CURLOPT_MIMEPOST, mime1);
  curl_easy_setopt(hnd, CURLOPT_USERAGENT, "curl/7.60.0");
  curl_easy_setopt(hnd, CURLOPT_MAXREDIRS, 50L);
  curl_easy_setopt(hnd, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2TLS);
  curl_easy_setopt(hnd, CURLOPT_SSH_KNOWNHOSTS, "/home/MY_USER/.ssh/known_hosts");
  curl_easy_setopt(hnd, CURLOPT_TCP_KEEPALIVE, 1L);

  ret = curl_easy_perform(hnd);

  curl_easy_cleanup(hnd);
  hnd = NULL;
  curl_mime_free(mime1);
  mime1 = NULL;

  return (int)ret;
}