Reputation: 47
I succeed to upload an image file to my blog by using curl command like this.
curl -F 'access_token=xxx' -F 'blogName=xxx' -F '[email protected]' https://www.tistory.com/apis/post/attach
And... to use it on my c++ project, I converted it to libcurl like this.
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);
...
}
This converted code doesn't work. And the result is response code 400. Actually I don't know what function of libcurl is correspond to -F option of curl command. Somebody let me know how to convert this curl command at the top to libcurl, or what function do I have to study about. Thanks in advance.
Upvotes: 0
Views: 633
Reputation: 2741
After running the following command (useful life hack here!):
curl -F 'access_token=xxx' -F 'blogName=xxx' -F '[email protected]' https://www.tistory.com/apis/post/attach --libcurl example.cc && cat example.cc
I got the following code (tidied up a bit for legibility on 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;
}
Upvotes: 1