腾格里

程序员交流学习的网站
站长QQ:540329378

c++ libcurl上传图片

int HttpPostFile(const std::string &strUrl,std::string path,std::string filename, std::string &strResponse, int nTimeout) {

curl_global_init(CURL_GLOBAL_ALL);
CURL *hnd = curl_easy_init();
CURLcode ret;

curl_easy_setopt(hnd, CURLOPT_URL, strUrl.c_str());

struct curl_slist *headers = NULL;

struct curl_httppost* formpost = NULL;
struct curl_httppost* lastptr = NULL;

headers = curl_slist_append(headers, "Content-Type: multipart/form-data");

curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);

curl_formadd(&formpost, &lastptr,CURLFORM_PTRNAME, "image", CURLFORM_FILE, path.c_str(), CURLFORM_FILENAME,filename.c_str(), CURLFORM_END);    // 设置要上传的文件

//curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"image\"; filename=\"D:\\code\\2.jpg\"\r\nContent-Type: image/png\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--");

curl_easy_setopt(hnd, CURLOPT_HTTPPOST, formpost);

ret = curl_easy_setopt(hnd, CURLOPT_TIMEOUT, nTimeout);

ret = curl_easy_setopt(hnd, CURLOPT_WRITEFUNCTION, receive_data);

ret = curl_easy_setopt(hnd, CURLOPT_WRITEDATA, (void*)&strResponse);

ret = curl_easy_perform(hnd);

if (ret != CURLE_OK)
{
    // 获取详细错误信息
    const char* szErr = curl_easy_strerror(ret);
    fprintf(stderr, "curl_easy_perform() failed: %s\n", szErr);
}

curl_easy_cleanup(hnd);
return ret;

}

未经允许不得转载:腾格里 » c++ libcurl上传图片

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址