我成功地使用这样的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
我得到了以下代码(为了在SO上易读性而整理了一些(:
#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;
}