看看这个功能:
string PostFile(string link, string filename, string postfilename){
CURL *curl;
CURLcode res;
string readBuffer;
struct curl_httppost *formpost = NULL;
struct curl_httppost *lastptr = NULL;
struct curl_slist *headerlist = NULL;
static const char buf[] = "Expect :";
curl_global_init(CURL_GLOBAL_ALL);
curl_formadd(&formpost,
&lastptr,
CURLFORM_COPYNAME, postfilename.c_str(),
CURLFORM_FILE, filename.c_str(),
CURLFORM_END);
curl_formadd(&formpost,
&lastptr,
CURLFORM_COPYNAME, "filename",
CURLFORM_COPYCONTENTS, filename.c_str(),
CURLFORM_END);
curl = curl_easy_init();
headerlist = curl_slist_append(headerlist, buf);
if(!curl) return "Error";
curl_easy_setopt(curl, CURLOPT_URL, link.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
res = curl_easy_perform(curl);
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
curl_easy_cleanup(curl);
curl_formfree(formpost);
curl_slist_free_all (headerlist);
return readBuffer;
}
使用后
PostFile("http://ilovedyourmother.ga/data/test/upload.php", "LOL.txt", "uploadfile");
它会像这样返回错误
curl_easy_perform() failed: Failed to open/read local data from file/application
这个函数基于curl postit2.c示例(http://curl.haxx.se/libcurl/c/postit2.html),实际上我不太明白它是如何工作的。请在这段代码中找到错误或者至少解释一下它的作用。
答案 0 :(得分:0)
我遇到了同样的问题。指定CURLFORM_FILE的绝对路径并在此之后添加CURLFORM_FILENAME选项并仅为该选项提供文件名,如下所示。
curl_formadd(&formpost,
&lastptr,
CURLFORM_COPYNAME, "image_data",
CURLFORM_FILE, "/home/user/TestImages/123.jpg",
CURLFORM_FILENAME, "123.jpg",
CURLFORM_CONTENTTYPE, "image/jpeg",
CURLFORM_END);